避免在Java中使用String.format("%。2f" doubleValue)四舍五入 [英] Prevent round off in String.format("%.2f", doubleValue) in Java

查看:3063
本文介绍了避免在Java中使用String.format("%。2f" doubleValue)四舍五入的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何防止 String.format(%。2f,doubleValue); 四舍五入(round half up algorithm),而不是截断它?例如

  doubleValue = 123.459 



格式化后,

  doubleValue = 123.46 

我只想放弃最后一位数字,

  123.45 

我知道还有其他方法可以做这个,我只是想知道这是否可以使用String.format。

解决方案

您可以随时设置舍入模式:



http://java.sun.com/javase/6/docs/api/java/math/RoundingMode.html 然后用String
$ b

然后用String .Format()
默认情况下使用HALF_EVEN,但可以将其更改为CEILING另一种没有如此灵活的方法wi (但这不是你所问的):
$ b $ $ $ pre $ DecimalFormat df = DecimalFormat(###。## );
df.format(123.459);


How do I prevent String.format("%.2f", doubleValue); from rounding off (round half up algorithm) instead of just truncating it?

e.g.

doubleValue = 123.459

after formatting,

doubleValue = 123.46

I just want to discard the last digit,

123.45

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

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)四舍五入的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆