Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

.net

double

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

like image 797
Mahesh Avatar asked Jan 05 '11 14:01

Mahesh


People also ask

How do you get rid of decimal point in double value?

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.

How do you round a double to two decimal places in C#?

double inputValue = 48.00; inputValue = Math. Round(inputValue, 2); will result 48 only.

How do I get the number after the decimal point in C#?

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.

How do you find a fractional part of a number in C?

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.


1 Answers

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.

like image 55
Nellius Avatar answered Sep 19 '22 06:09

Nellius