拖放浮点数的尾部数字 [英] Drop trailing digits of a floating point number
问题描述
float var1 = 1.23456f;
float var2 = 2.34567f;
在我的计算中,浮点型变量中小数点后的位数增加和减少以保持精度。例如,经过一些计算
System.out.println(var1);
可能会打印:
6.35
或
9.4500082E
或
88.25214
我想将这些值四舍五入到小数点后三位,然后删除后面的十进制数字,以便浮点四舍五入:
6.350 9.450 88.252
据我所知,NumberFormat和String.format()以格式化的字符串返回输出。我怎样才能得到输出为四舍五入浮动使用它在我的计算进一步?
我可以应用一个规则到我的浮动(浮动)变量(实例)总是四舍五入/小数点后三位数字?
不,你不能得到一个四舍五入的浮点数。 float
不存储十进制数字。使用 BigDecimal
如果你想使用特定的小数位数进行计算。
其他的答案都不会得到你想要的东西。
I have some float variables in my java program:
float var1=1.23456f;
float var2=2.34567f;
In my calculations, the number of digits after decimal point in my float variable increases and decreases to maintain precision. for e.g. after some calculations System.out.println(var1); may print:
6.35
or
9.4500082E
or
88.25214
I want to round off these values to 3 decimal places and drop the subsequent decimal digits so that float gets rounded off like:
6.350 9.450 88.252
As far as i know, The NumberFormat and String.format() return the output as formatted String. How can i get the output as rounded off float to use it further in my calculations? Can i apply a rule to my float(Float) variables(Instance) to always round-off/drop the trailing digits after 3 decimal places?
No, you can't get a "rounded off float." A float
doesn't store a decimal number. Use BigDecimal
if you want to do calculations using a specific number of decimal digits.
None of the other answers will get you what you actually want.
这篇关于拖放浮点数的尾部数字的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!