Java - 如何将计算语句结果舍入为两位有效数字

Java新手,对编程相对较新。下面的代码是已经完美运行的程序的最后几行 - 我只想将最终结果(newTuition变量)四舍五入,并将其限制为两个有效数字。Java - 如何将计算语句结果舍入为两位有效数字

newTuition,TUITIONINCREASE和学费都是双打。

newTuition = ((TUITIONINCREASE * .01) * tuition) + tuition + "."); 

System.out.println("Your current tuition is $" + tuition + ". It will rise next year by " + TUITIONINCREASE + "% and " +

"your new tuition will be $" + newTuition);

回答:

使用BigDecimal.Round:http://docs.oracle.com/javase/1.5.0/docs/api/java/math/BigDecimal.html#round(java.math.MathContext

像这样:

BigDecimal rounded = value.round(new MathContext(2, RoundingMode.HALF_UP)); 

System.out.println(value + ": " + rounded);

回答:

提意见是正确的。不要为此使用浮点数。你需要的是BigDecimal类。这将在数​​学运算中为您保留精度,并且包含四舍五入和截断的方法。

http://docs.oracle.com/javase/7/docs/api/java/math/BigDecimal.html

以上是 Java - 如何将计算语句结果舍入为两位有效数字 的全部内容, 来源链接: utcz.com/qa/260669.html

回到顶部