开发者

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

开发者 https://www.devze.com 2023-02-02 07:57 出处:网络
I would like to get the decimal value from a double value. For example: 23.456 ->0.456 11.开发者_运维技巧23->0.23

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#??

Thanks, Mahesh


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.

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.

n - Math.Truncate(n) would give 0.3 for both 12.3 and -12.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.


x - Math.Floor(x);

text to bring up to 30 chars


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.

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.

[/EDIT]

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


I use this method when i calculate offsets.

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


Try this.

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

精彩评论

暂无评论...
验证码 换一张
取 消