如何在Java中格式化双输入而不进行舍入? [英] How do I format double input in Java WITHOUT rounding it?
问题描述
我已经阅读了这个问题将一个小数加倍到2位小数它显示了如何舍入数字。我想要的只是简单的格式化,只打印两个小数位。
我有什么和我尝试过的:
double res = 24.695999999999998;
DecimalFormat df = new DecimalFormat(#### 0.00);
System.out.println(Value:+ df.format(res)); //打印24.70,我想要24.69
System.out.println(Total:+ String.format(%。2f,res)); //打印24.70
所以当我有24.695999999999998时我想将其格式化为24.69
您需要首先获取double值的 floor
- 然后格式化它。 / p>
返回最大(最接近正无穷大)双精度值小于或等于参数且等于数学整数。
所以使用类似:
double v = Math.floor(res * 100)/ 100.0;
其他替代方案包括使用 BigDecimal
。
public void test(){
double d = 0.29;
System.out.println(d =+ d);
System.out.println(floor(d * 100)/ 100 =+ Math.floor(d * 100)/ 100);
System.out.println(BigDecimal d =+ BigDecimal.valueOf(d).movePointRight(2).round(MathContext.UNLIMITED).movePointLeft(2));
}
打印
d = 0.29
楼(d * 100)/100=0.28
BigDecimal d = 0.29
I have read this question Round a double to 2 decimal places It shows how to round number. What I want is just simple formatting, printing only two decimal places. What I have and what I tried:
double res = 24.695999999999998;
DecimalFormat df = new DecimalFormat("####0.00");
System.out.println("Value: " + df.format(res)); //prints 24.70 and I want 24.69
System.out.println("Total: " + String.format( "%.2f", res )); //prints 24.70
So when I have 24.695999999999998 I want to format it as 24.69
You need to take the floor
of the double value first - then format it.
Returns the largest (closest to positive infinity) double value that is less than or equal to the argument and is equal to a mathematical integer.
So use something like:
double v = Math.floor(res * 100) / 100.0;
Other alternatives include using BigDecimal
.
public void test() {
double d = 0.29;
System.out.println("d=" + d);
System.out.println("floor(d*100)/100=" + Math.floor(d * 100) / 100);
System.out.println("BigDecimal d=" + BigDecimal.valueOf(d).movePointRight(2).round(MathContext.UNLIMITED).movePointLeft(2));
}
prints
d=0.29
floor(d*100)/100=0.28
BigDecimal d=0.29
这篇关于如何在Java中格式化双输入而不进行舍入?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!