我想截断 Java 中的浮点值。
以下是我的要求:
- 如果我有 12.49688f,它应该打印为 12.49 而不四舍五入
- 如果是双精度的 12.456,应该打印为 12.45 不四舍五入
- 在任何情况下,如果该值类似于 12.0,则应仅将其打印为 12。
条件3要始终牢记。它应该与截断逻辑同时发生。
PS:我正在使用 Java 1.5 。所以我知道如何在 Java 1.6 中做到这一点,即使用十进制格式和调用setroundingMode ()方法。我需要了解 Java 1.5
在将数字提供给 DecimalFormat 之前,使用Math#floor和除法进行乘法运算。这与截止圆角相同。
// Replace N with the desired number of decimals after the comma
number = Math.floor(1eN * number) / 1eN
由于浮点计算中的舍入错误,这并不完美,因此您仍然必须为 DecimalFormat 指定 N 个小数。
一种(更昂贵,但也更合乎逻辑)的替代方法是使用BigDecimal。
// Given as seperate statements for clarity, but these can be combined into a single line
// Replace "N" with the number of decimals after the comma
MathContext NDecimals = new MathContext(N, RoundingMode.FLOOR);
BigDecimal bdNumber = new BigDecimal(number, NDecimals);
number = bdNumber.doubleValue();
将其转换为字符串并截断句点后第二个数字之后的任何内容。修剪“0”和“.” 如果有一个“。”
String x = Double.toString (12.456); // or Float.toString (12.49688f);
int pos = x.indexOf ('.'); //
if (pos >= 0) {
int end = Math.min(pos + 2, x.length() - 1); // truncate after 2 digits
while (x.charAt (end) == '0') end --; // trim 0
if (x.charAt (end) == '.') end --; // trim .
x = x.substring(0, end + 1); // really truncate
}
(经过测试,在我的环境中工作)