Java 十进制格式无效
我想确保一个数字只有两位小数 例如,输入的面积=256.12345,因此面积为256.12 这就是我所拥有的:Java 十进制格式无效,java,decimal,number-formatting,Java,Decimal,Number Formatting,我想确保一个数字只有两位小数 例如,输入的面积=256.12345,因此面积为256.12 这就是我所拥有的: DecimalFormat df = new DecimalFormat( "#,###,###,##0.00" ); double area = new Double(area.format(area)).doubleValue(); area = (double)(r*r); 您实际上没有使用实例df 将代码更改为使用它,而不是在区域上调用方法(这不起作用,因为原语没有方法):
DecimalFormat df = new DecimalFormat( "#,###,###,##0.00" );
double area = new Double(area.format(area)).doubleValue();
area = (double)(r*r);
您实际上没有使用实例
df
将代码更改为使用它,而不是在区域
上调用方法(这不起作用,因为原语没有方法):
但是,精度的形式更多地用于打印目的,而不是存储目的(Double
将其存储在IEEE双精度浮点标准中,这可能导致不精确的浮点值)
若要避开此问题,请使用精度为2的BigDecimal
:
BigDecimal decimal = new BigDecimal(area);
decimal.setScale(2);
System.out.println(decimal); // will print area to two decimal places
你就是这样做的
//formatting numbers upto 2 decimal places in Java
DecimalFormat df = new DecimalFormat("#,###,##0.00");
System.out.println(df.format(364565.14));
System.out.println(df.format(364565.1454));
//formatting numbers upto 3 decimal places in Java
df = new DecimalFormat("#,###,##0.000");
System.out.println(df.format(364565.14));
System.out.println(df.format(364565.1454));
}
}
Output:
364,565.14
364,565.15
364,565.140
364,565.145
您在哪里使用
df
?
//formatting numbers upto 2 decimal places in Java
DecimalFormat df = new DecimalFormat("#,###,##0.00");
System.out.println(df.format(364565.14));
System.out.println(df.format(364565.1454));
//formatting numbers upto 3 decimal places in Java
df = new DecimalFormat("#,###,##0.000");
System.out.println(df.format(364565.14));
System.out.println(df.format(364565.1454));
}
}
Output:
364,565.14
364,565.15
364,565.140
364,565.145