Java浮点数学 – (转换为英尺/米)
我认为非常基本的问题 – 我正在执行此function:
private double convertMetersToFeet(double meters) { //function converts Feet to Meters. double toFeet = meters; toFeet = meters*3.2808; // official conversion rate of Meters to Feet return toFeet; }
问题是输出; 例如,我从101的输入得到337.36080000000004。截断浮点的适当做法是什么?
如下面的答案所假设,我希望4个有效数字与我的转换率保持一致。
您可以使用NumberFormat实例。
NumberFormat nf = NumberFormat.getInstance(Locale.UK); nf.setMinimumFractionDigits(4); nf.setMaximumFractionDigits(4); System.out.println(nf.format(feet));
或者您可以使用DecimalFormat 。
DecimalFormat df = new DecimalFormat("0.0000"); System.out.println(df.format(feet));
后者(DecimalFormat)将在您明确要声明格式时使用,而前者(NumberFormat)则在需要本地化设置时使用。
对于四个一致的小数,如果您没有长距离工作,则无需拖动BigDecimal。
我为了后人的缘故回答了我自己的问题。 我使用了上面的DecimalFormat答案,但答案没有考虑到方法的返回类型。
这是完成的代码:
private double convertMetersToFeet(double meters) { //function converts Feet to Meters. double toFeet = meters; toFeet = meters*3.2808; // official conversion rate of Meters to Feet String formattedNumber = new DecimalFormat("0.0000").format(toFeet); //return with 4 decimal places double d = Double.valueOf(formattedNumber.trim()).doubleValue(); return d; }
如果需要精确计算,请使用BigDecimal而不是float。 如果您只想在打印时截断,请使用DecimalFormat 。
DecimalFormat df = new DecimalFormat ("0.00"); System.out.println(df.format(convertMetersToFeet(101)));
使用java.math.BigDecimal
进行十进制算术运算。
如果不是用于打印,则不应该关心错误。 337.36080000000004与337.3608一样正确,因为因子中只有5位有效数字,测试输入中只有3位。 (我当然希望你的方法给出的答案是331而不是337)
然而,从另一个问题中获取的这条线似乎也可以解决问题 。
double toFeet = ((int)(meters*3.2808*10000))/10000.0;
唯一的问题是溢出速度快得多。