Java Modulo运算符

时间:2012-10-09 17:36:34

标签: java modulo

  

可能重复:
  Floating point inaccuracy examples

在java中使用modulo运算符时,我没有得到我希望获得的数字。

继续我正在做的事情:

double input = 5.59;
System.out.println("Output: " + (input % 2));

我希望看到1.59作为结果,但它打印出1.5899999999999999。关于为什么会这样的任何线索?

2 个答案:

答案 0 :(得分:5)

这来自浮点不准确,here is a great SO answer explaining exactly what is happening.

如果您希望它能够使用这样的格式来完善数字:

double input = 5.59;
System.out.format("Output: %.2f%n", (input % 2));
  • “%”告诉格式化程序用第一个数字参数替换自身。您可以根据需要添加任意数量的这些内容。
  • “。2”告诉格式化程序格式化小数点后两位的数字。
  • “f”告诉格式化程序它是一个浮点数。
  • “%n”是适合运行应用程序的平台的新行字符。您应该始终使用“%n”,而不是“\ n”。

Here is some good documentation for all this.

希望这有帮助!

答案 1 :(得分:1)

因为Double的精确度。您需要对其进行格式化以获得所需的输出。

double input = 5.59;
System.out.println("Output: " + new DecimalFormat("00.00").format(input % 2));

它将打印输出:1.59

相关问题