Java浮点数学 - (转换为英尺/米) [英] Java floating point math - (conversion for feet/meters)

查看:151
本文介绍了Java浮点数学 - (转换为英尺/米)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

  private double convertMetersToFeet(double meters)
{
//函数将脚转换成米。
double toFeet = meters;
toFeet =米* 3.2808; //米到英尺的官方转换率
返回到脚;

问题是输出;例如我从输入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。

Pretty basic question I think - I'm performing this 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;
}

Problem is the output; for example I get 337.36080000000004 from an input of 101. What's the appropriate practice for truncating the floating points?

As the answers below assumed, I'd want 4 significant figures to remain consistent with my conversion ratio.

解决方案

You can use a NumberFormat instance.

NumberFormat nf = NumberFormat.getInstance(Locale.UK);
nf.setMinimumFractionDigits(4);
nf.setMaximumFractionDigits(4);
System.out.println(nf.format(feet));

Or you can use DecimalFormat.

DecimalFormat df = new DecimalFormat("0.0000");
System.out.println(df.format(feet));

The latter (DecimalFormat), is to be used when you explicitly want to state the format and the former (NumberFormat), when want localized settings.

For four consistent fractional figures, there is no need to drag in BigDecimal, if your aren't working with really long distances.

这篇关于Java浮点数学 - (转换为英尺/米)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆