[英]Java - how to round a calculation statement result to two significant figures
Java的新手,编程的新手。 下面的代码是已经完美运行的程序的最后几行-我只想舍入最终结果(newTuition变量)并将其限制为两个有效数字。
newTuition,TUITIONINCREASE和tuition均为双精度。
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类。 这将在数学运算期间为您保留精度,并包含用于舍入和截断的方法。
http://docs.oracle.com/javase/7/docs/api/java/math/BigDecimal.html
使用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);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.