![](/img/trans.png)
[英]Preserving Accuracy When Formatting a Floating Point Number to Display With Two-point Precison (Java)
[英]Formatting Floating point number in java upto 3 precison of decimal
我有一个变量类型float.I想要打印到3精度的十进制,包括尾随零。
示例:
2.5 >> 2.500
1.2 >> 1.200
1.3782 >> 1.378
2 >> 2.000
我正在尝试使用它
DecimalFormat _numberFormat= new DecimalFormat("#0.000");
Float.parseFloat(_numberFormat.format(2.5))
但它没有转换2.5 >> 2.500。
难道我做错了什么..
请帮忙..
这是错误Float.parseFloat
这是转换回2.5
_numberFormat.format(2.5)
输出为2.500
但是这个Float.parseFloat
使它回到了2.5
所以你的代码必须是
DecimalFormat _numberFormat= new DecimalFormat("#0.000");
_numberFormat.format(2.5)
尝试格式如下:
DecimalFormat df = new DecimalFormat();
df.applyPattern(".000");
System.out.println(df.format(f));
您正在为格式化的字符串写入小数,然后将其解析为浮点数。
如果它们读取2.500或2.5,浮点数并不在意,尽管前者是格式化的。
由于IEEE754无法处理指定重要数据的数量,因此浮点数不会保留尾随零。
尝试
System.out.printf("%.3f", 2.5);
printf-Method允许您指定输入的格式。 在这种情况下, %.3f
表示
将以下数字打印为带有3位小数的浮点数
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.