Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get the numbers after the decimal point? (java) [duplicate]

Tags:

 double d = 4.321562; 

Is there an easy way to extract the 0.321562 on it's own from d? I tried looking in the math class but no luck. If this can be done without converting to string or casting to anything else, even better.

like image 418
David Avatar asked May 29 '11 08:05

David


People also ask

How do you find the number after a decimal point?

The first digit after the decimal represents the tenths place. The next digit after the decimal represents the hundredths place. The remaining digits continue to fill in the place values until there are no digits left. The number.

How do I print 2 digits after a decimal?

printf("%. 2f", value); The %. 2f syntax tells Java to return your variable (value) with 2 decimal places (.

Can double take decimal values in Java?

Both Double and float data type are used to represent floating-point numbers in Java; a double data type is more precise than float. A double variable can provide precision up to 15 to 16 decimal points as compared to float precision of 6 to 7 decimal digits.


1 Answers

Well, you can use:

double x = d - Math.floor(d); 

Note that due to the way that binary floating point works, that won't give you exactly 0.321562, as the original value isn't exactly 4.321562. If you're really interested in exact digits, you should use BigDecimal instead.

like image 198
Jon Skeet Avatar answered Sep 29 '22 20:09

Jon Skeet