Java转换format.String
发布时间:2020-12-15 04:36:29 所属栏目:Java 来源:网络整理
导读:我还是 Java的新手,我想知道是否有任何方法可以格式化为双精度而不进行舍入? 例: double n = 0.12876543;String s = String.format("%1$1.2f",n); 如果我打印到系统,它将返回0.13而不是精确的0.12.现在我想到了一个解决方案,但我想知道是否有更好的方法来
我还是
Java的新手,我想知道是否有任何方法可以格式化为双精度而不进行舍入?
例: double n = 0.12876543; String s = String.format("%1$1.2f",n); 如果我打印到系统,它将返回0.13而不是精确的0.12.现在我想到了一个解决方案,但我想知道是否有更好的方法来做到这一点.这是我简单的解决方案 double n = 0.12876543; double n = Double.parseDouble(String.format(("%1$1.2f",n)); 还有其他想法或解决方案? 解决方法
一个优雅的解决方案是将setRoundingMode与DecimalFormat一起使用.它适当地设置RoundingMode.
例如: // Your decimal value double n = 0.12876543; // Decimal Formatting DecimalFormat curDf = new DecimalFormat(".00"); // This will set the RoundingMode curDf.setRoundingMode(RoundingMode.DOWN); // Print statement System.out.println(curDf.format(n)); 输出: 0.12 此外,如果要将其他格式设置为字符串,则可以始终将double值更改为字符串: // Your decimal value double n = 0.12876543; // Decimal Formatting DecimalFormat curDf = new DecimalFormat(".00"); // This will set the RoundingMode curDf.setRoundingMode(RoundingMode.DOWN); // Convert to string for any additional formatting String curString = String.valueOf(curDf.format(n)); // Print statement System.out.println(curString); 输出: 0.12 请在此处参考类似的解决方案:https://stackoverflow.com/a/8560708/4085019 (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |