如何获得小数点后的数字?(Java)的

Dav*_*vid 24 java math double numbers decimal-point

 double d = 4.321562;
Run Code Online (Sandbox Code Playgroud)

有没有一种简单的方法从d中提取0.321562?我试着看数学课,但没有运气.如果这可以在不转换为字符串或转换为其他任何内容的情况下完成,甚至更好.

Jon*_*eet 30

好吧,你可以使用:

double x = d - Math.floor(d);
Run Code Online (Sandbox Code Playgroud)

需要注意的是,由于方式二进制浮点的行为,不会给你确切 0.321562,与原始值不准确 4.321562.如果你真的对确切的数字感兴趣,你应该使用BigDecimal.

  • 不要使用它,改为铸造:`x - (int)x`.使用正数和负数都可以正确地进行转换.否则,`Math.floor()`将使用"最大正(最接近正无穷大)整数值小于或等于参数".示例:`-123.25 - (int)( - 123.25)`将导致-0.25,因此您可以决定如何处理符号.使用`Math.floor()`会给出'0.75'的正数 (2认同)

Pet*_*rey 27

在不使用Math的情况下获得分数的另一种方法是强制转换为long.

double x = d - (long) d;
Run Code Online (Sandbox Code Playgroud)

打印时double,toString将执行少量舍入,因此您不会看到任何舍入错误.但是,当您删除整数部分时,舍入不再足够,并且舍入错误变得明显.

解决这个问题的方法是自己进行舍入或使用允许您控制舍入的BigDecimal.

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));
Run Code Online (Sandbox Code Playgroud)

版画

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
Run Code Online (Sandbox Code Playgroud)


Ced*_*ach 9

使用模数:

double d = 3.123 % 1;
assertEquals(0.123, d,0.000001);
Run Code Online (Sandbox Code Playgroud)