Java floating point math - (conversion for feet/meters)

前端 未结 5 536
爱一瞬间的悲伤
爱一瞬间的悲伤 2021-01-20 16:36

Pretty basic question I think - I\'m performing this function:

private double convertMetersToFeet(double meters)
{
  //function converts Feet to Meters.
             


        
5条回答
  •  清歌不尽
    2021-01-20 17:04

    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.

提交回复
热议问题