java 米转换公里,Java浮点数学 - (转换为英尺/米)

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.

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值