【问题标题】:Printing first 3 decimal places without rounding打印前 3 位小数,不四舍五入
【发布时间】:2015-08-31 02:23:48
【问题描述】:

好的,我知道已经有一个非常相似的问题,但它并没有完全回答我的问题。如果我做错了什么,请告诉我。

我编写了一个程序,从用户那里获取华氏温度并将其转换为摄氏度。它看起来像这样:

import java.util.Scanner;

public class FahrenheitToCelcius {

    public static void main(String[] args) {

        double fahrenheit;
        Scanner sc = new Scanner(System.in);

        System.out.print("Please enter a temperature in Fahrenheit: ");

        fahrenheit = sc.nextDouble();  
        double celcius = (fahrenheit - 32) * 5 / 9;

        String num = String.format("%.3f", celcius);

        System.out.println(" ");
        System.out.println(fahrenheit + "F" + " is " + num + "C");
    } 
}

当它打印出答案时,我只想要打印前 3 位小数,而不是四舍五入。例如,如果输入是100F,我想打印37.777C不是 37.778C

我尝试过使用DecimalFormatString.format(如上),但两种方法都会打印出37.778C。有没有更好的方法来做到这一点?

感谢您的回答,如有重复,我深表歉意。

【问题讨论】:

  • 感谢您的编辑,约翰。

标签: java floating-point rounding


【解决方案1】:

您可以使用DecimalFormat,只需设置RoundingMode

DecimalFormat df = new DecimalFormat("#.###");
df.setRoundingMode(RoundingMode.FLOOR);
String num = df.format(celcius);

【讨论】:

    【解决方案2】:

    将摄氏度乘以 1000 将小数点移动 3 位

    celsius = celsius * 1000;
    

    现在将数字取底并除以 1000

    celsius = Math.floor(celsius) / 1000;    
    

    它将不再需要 String.format() 方法。

    【讨论】:

      【解决方案3】:

      这个答案类似于使用 Math.floor 但可能更容易转换为 int:

      想要两位小数?试试这个:

      System.out.println( (int) (your_double * 100) / 100.0 );

      想要 3 位小数?试试这个:

      System.out.println( (int) (your_double * 1000) / 1000.0 );

      想要 4 位小数?试试这个:

      System.out.println( (int) (your_double * 10000) / 10000.0 );

      看到模式了吗?将你的双倍乘以 10 到你想要的小数位数的幂。转换后,除以相同的十进制零。

      【讨论】:

        【解决方案4】:

        您可以简单地四舍五入到小数点后 4 位,然后修剪最后一个字符。

        String num = String.format("%.4f", celcius);
        
        num = num.substring(0, num.length() - 1);
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2011-03-09
          • 1970-01-01
          • 2020-06-24
          • 1970-01-01
          • 2014-10-10
          相关资源
          最近更新 更多