Java 如何在双打中将小数设置为仅 2 位?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/16191734/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-16 05:42:18  来源:igfitidea点击:

How to set decimals to only 2 digits in Doubles?

javaandroid

提问by theJava

In my response i am getting the value as 80.00000

在我的回应中,我得到的价值为 80.00000

DecimalFormat df = new DecimalFormat("##.##");
TextField.setText(df.format(Double.parseDouble(custom.getValue())));

My problem is i am getting 80.000, i am doing a parseDouble which will return a primitive double type and i am doing a format to this double to 2 decimals.

我的问题是我得到了 80.000,我正在做一个 parseDouble 它将返回一个原始的 double 类型,我正在做一个格式到这个 double to 2 decimals.

Why am i getting 80instead of 80.00?

为什么我得到80而不是80.00

I changed my way and tried with this.

我改变了我的方式并尝试了这个。

TextField.setText(String.format("%2f",Double.parseDouble(custom.getValue()))); 

Now i am geting 80.000000instead of 80.00

现在我得到80.000000而不是80.00

采纳答案by Blackbelt

Should be "%.2f"instead of "%2f"

应该"%.2f"代替"%2f"

TextField.setText(String.format("%.2f",Double.parseDouble(custom.getValue())));

you forget to add the .

你忘记添加 .

回答by Reimeus

Why am i getting 80 instead of 80.00?

为什么我得到的是 80 而不是 80.00?

The first example should be:

第一个例子应该是:

DecimalFormat df = new DecimalFormat("##.00");

Otherwise any non significant fractional digits will be suppressed.

否则任何非有效小数位将被抑制。

回答by Mihir Shah

Change %2fto %.2fin the String.format parameter.

在 String.format 参数中更改%2f%.2f

回答by cahen

java.text.NumberFormatis a good alternative

java.text.NumberFormat是一个不错的选择

final NumberFormat nf = NumberFormat.getInstance();
nf.setMinimumFractionDigits(2);
nf.setMaximumFractionDigits(2);
nf.setGroupingUsed(false);
System.out.println(nf.format(123456789.123456789));