.net 如何从C#中的double值获取小数点后的值?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/4604980/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-03 15:05:59  来源:igfitidea点击:

How to get value after decimal point from a double value in C#?

.netdouble

提问by Mahesh

I would like to get the decimal value from a double value.

我想从双精度值中获取十进制值。

For example:

例如:

23.456 ->  0.456
11.23  ->  0.23

Could anyone let me know how to do this in C#??

谁能让我知道如何在 C# 中做到这一点?

Thanks, Mahesh

谢谢,马赫什

采纳答案by sharepointmonkey

x - Math.Floor(x);

x - Math.Floor(x);

text to bring up to 30 chars

最多 30 个字符的文本

回答by Nellius

There is no Method in System.Math that specifically does this, but there are two which provide the way to get the integer part of your decimal, depending on how you wish negative decimal numbers to be represented.

System.Math 中没有专门执行此操作的方法,但有两种方法提供了获取小数的整数部分的方法,具体取决于您希望如何表示负十进制数。

Math.Truncate(n)will return the number before the decimal point. So, 12.3 would return 12, and -12.3 would return -12. You would then subtract this from your original number.

Math.Truncate(n)将返回小数点前的数字。因此,12.3 将返回 12,-12.3 将返回 -12。然后,您将从原始数字中减去该数字。

n - Math.Truncate(n)would give 0.3 for both 12.3 and -12.3.

n - Math.Truncate(n)将为 12.3 和 -12.3 提供 0.3。

Using similar logic, Math.Floor(n)returns the whole number lower than the decimal point, and Math.Ceiling(n)returns the whole number higher than the decimal point. You can use these if you wish to use different logic for positive and negative numbers.

使用类似的逻辑,Math.Floor(n)返回小于小数点的整数,Math.Ceiling(n)返回大于小数点的整数。如果您希望对正数和负数使用不同的逻辑,则可以使用这些。

回答by W.Hymanson

This is what the modulus operator (%) is for. It gives you the remainer when dividing the first operand by the second. Just divide the number you want the decimal of by 1.

这就是模运算符 (%) 的用途。当第一个操作数除以第二个操作数时,它会为您提供剩余部分。只需将您想要小数的数字除以 1。

Ex:

前任:

decimal d = new Decimal(23.456);
d = d % 1;

// d = 0.456

[EDIT]

[编辑]

After reading Nellius's comment about my post I tested it out. When using doubles the modulus operator actually returns 0.45599999999999952. My answer is in fact incorrect.

在阅读了 Nellius 对我的帖子的评论后,我对其进行了测试。使用 double 时,模运算符实际上返回 0.45599999999999952。我的回答实际上是错误的。

[/EDIT]

[/编辑]

Reference: http://msdn.microsoft.com/en-us/library/0w4e0fzs.aspx

参考:http: //msdn.microsoft.com/en-us/library/0w4e0fzs.aspx

回答by Thomas Andreè Wang

I use this method when i calculate offsets.

我在计算偏移量时使用这种方法。

double numberToSplit = 4.012308d;
double decimalresult = numberToSplit - (int)numberToSplit; //4.012308 - 4 = 0.012308

回答by ram nainar

Try this.

尝试这个。

    Dim numberToSplit As Double = 4.52121
    Dim decimalresult As Double = numberToSplit - Convert.ToInt64(numberToSplit)
    MsgBox(decimalresult)