打印前三位小数而不四舍五入 [英] Printing first 3 decimal places without rounding

查看:67
本文介绍了打印前三位小数而不四舍五入的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

Okay, I know there is a question quite similar already, but it didn't quite answer my question. Please let me know if I'm doing something wrong though.

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

I have written a program that gets a temperature in Fahrenheit from the user and converts it to Celcius. It looks like this:

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.

When it prints the answer out, I want only the first 3 decimal places printed, but not rounded. For example, if the input is 100F, I want 37.777C printed, not 37.778C.

我尝试使用DecimalFormatString.format(如上),但是两种方法都可以打印出37.778C.有更好的方法吗?

I have tried using DecimalFormat and String.format (like above), but both methods print out 37.778C. Is there a better way to do this?

谢谢您的回答,对于重复的内容,我深表歉意.

Thank you for your answers, and I apologise if this is a duplicate.

推荐答案

您可以使用DecimalFormat,只需设置

You can use DecimalFormat, just set the RoundingMode:

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

这篇关于打印前三位小数而不四舍五入的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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