Prevent round off in String.format(quot;%.2fquot;, doubleValue) in Java(防止 Java 中 String.format(%.2f, doubleValue) 的舍入)
问题描述
如何防止 String.format("%.2f", doubleValue); 舍入(四舍五入算法)而不是截断它?
How do I prevent String.format("%.2f", doubleValue); from rounding off (round half up algorithm) instead of just truncating it?
例如
doubleValue = 123.459
格式化后,
doubleValue = 123.46
我只想丢弃最后一位,
123.45
我知道还有其他方法可以做到这一点,我只想知道这是否可以使用 String.format.
I know there are other ways to do this, I just want to know if this is possible using the String.format.
推荐答案
你可以随时设置舍入模式:
You can always set the rounding mode:
http://java.sun.com/javase/6/docs/api/java/math/RoundingMode.html
然后使用 String.Format()默认使用 HALF_EVEN,但您可以将其更改为 CEILING
and then use String.Format() HALF_EVEN is used by default, but you can change it to CEILING
另一种不太灵活的方法是(但这不是你问的):
another no so flexible approach will be (but this is not what you asked about):
DecimalFormat df = new DecimalFormat("###.##");
df.format(123.459);
这篇关于防止 Java 中 String.format("%.2f", doubleValue) 的舍入的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:防止 Java 中 String.format("%.2f", doubleValue) 的舍入
基础教程推荐
- 存储 20 位数字的数据类型 2022-01-01
- 问题http://apache.org/xml/features/xinclude测试日志4j 2 2022-01-01
- 无法复制:“比较方法违反了它的一般约定!" 2022-01-01
- 修改 void 函数的输入参数,然后读取 2022-01-01
- RabbitMQ:消息保持“未确认"; 2022-01-01
- 如何对 Java Hashmap 中的值求和 2022-01-01
- Struts2 URL 无法访问 2022-01-01
- Spring AOP错误无法懒惰地为此建议构建thisJoinPoin 2022-09-13
- 使用堆栈算法进行括号/括号匹配 2022-01-01
- REST Web 服务返回 415 - 不支持的媒体类型 2022-01-01
