在java中格式化浮点数高达3个十进制精度

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/18525410/
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-12 08:46:19  来源:igfitidea点击:

Formatting Floating point number in java upto 3 precison of decimal

javafloating-point-precision

提问by Abhay

I have a variable type float.I wanted to print it upto 3 precision of decimal including trailing zeros.

我有一个变量类型浮点数。我想将它打印到 3 个小数精度,包括尾随零。

Example :

例子 :

2.5 >> 2.500

2.5 >> 2.500

1.2 >> 1.200

1.2 >> 1.200

1.3782 >> 1.378

1.3782 >> 1.378

2 >> 2.000

2 >> 2.000

I am trying it by using

我正在尝试使用

DecimalFormat _numberFormat= new DecimalFormat("#0.000");
Float.parseFloat(_numberFormat.format(2.5))

But it is not converting 2.5 >> 2.500.

但它没有转换 2.5 >> 2.500。

Am I doing something wrong..

难道我做错了什么..

Please help..

请帮忙..

采纳答案by Tarsem Singh

Here is mistake Float.parseFloatthis is converting back to 2.5

Float.parseFloat这是转换回 2.5 的错误

Output of _numberFormat.format(2.5)is 2.500

的输出 _numberFormat.format(2.5)2.500

But this Float.parseFloatmakes it back to 2.5

但这Float.parseFloat使它回到2.5

So your code must be

所以你的代码必须是

DecimalFormat _numberFormat= new DecimalFormat("#0.000");
_numberFormat.format(2.5)

回答by nanofarad

You're writing a decimal to a formatted string then parsing it into a float.

您正在将小数写入格式化字符串,然后将其解析为浮点数。

Floats don't care if they read 2.500 or 2.5, although the former is formatted.

浮点数不关心它们读取的是 2.500 还是 2.5,尽管前者是格式化的。

The float is not going to hold trailing zeroes as IEEE754 cannot handle specifying the number of significant fihgures.

浮点数不会保留尾随零,因为 IEEE754 无法处理指定有效数字的数量。

回答by Vince

Try

尝试

System.out.printf("%.3f", 2.5);

The printf-Method allows you to specify a format for your input. In this case %.3fmeans

printf-Method 允许您为输入指定格式。在这种情况下%.3f意味着

Print the following number as a floating point number with 3 decimals

将以下数字打印为带 3 位小数的浮点数

回答by Debojit Saikia

Try formatting as below :

尝试格式化如下:

DecimalFormat df = new DecimalFormat();
df.applyPattern(".000");
System.out.println(df.format(f));