How to get the numbers after the decimal point? (j

2019-03-23 08:25发布

This question already has an answer here:

 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.

3条回答
贼婆χ
2楼-- · 2019-03-23 09:00

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.

查看更多
相关推荐>>
3楼-- · 2019-03-23 09:06

Use modulo:

double d = 3.123 % 1;
assertEquals(0.123, d,0.000001);
查看更多
家丑人穷心不美
4楼-- · 2019-03-23 09:12

Another way to get the fraction without using Math is to cast to a long.

double x = d - (long) d;

When you print a double the toString will perform a small amount of rounding so you don't see any rounding error. However, when you remove the integer part, the rounding is no longer enough and the rounding error becomes obvious.

The way around this is to do the rounding yourself or use BigDecimal which allows you to control the rounding.

double d = 4.321562;
System.out.println("Double value from toString " + d);
System.out.println("Exact representation " + new BigDecimal(d));
double x = d - (long) d;
System.out.println("Fraction from toString " + x);
System.out.println("Exact value of fraction " + new BigDecimal(x));
System.out.printf("Rounded to 6 places %.6f%n", x);
double x2 = Math.round(x * 1e9) / 1e9;
System.out.println("After rounding to 9 places toString " + x2);
System.out.println("After rounding to 9 places, exact value " + new BigDecimal(x2));

prints

Double value from toString 4.321562
Exact representation 4.321562000000000125510268844664096832275390625
Fraction from toString 0.3215620000000001
Exact value of fraction 0.321562000000000125510268844664096832275390625
Rounded to 6 places 0.321562
After rounding to 9 places toString 0.321562
After rounding to 9 places, exact value 0.32156200000000001448796638214844278991222381591796875
查看更多
登录 后发表回答