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
Truncation Using Casting If our double value is within the int range, we can cast it to an int. The cast truncates the decimal part, meaning that it cuts it off without doing any rounding.
double inputValue = 48.00; inputValue = Math. Round(inputValue, 2); will result 48 only.
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.
In the C Programming Language, the modf function splits a floating-point value into an integer and a fractional part. The fraction is returned by the modf function and the integer part is stored in the iptr variable.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With