将Double值格式化为2个小数位的最佳方法 [英] Best way to Format a Double value to 2 Decimal places

查看:840
本文介绍了将Double值格式化为2个小数位的最佳方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述


可能重复:

小数点后的双倍到2位有效数字

我在应用程序中处理了很多双值,是否有简单的方法来处理Java中十进制值的格式?

I am dealing with lot of double values in my application, is there is any easy way to handle the formatting of decimal values in Java?

还有其他更好的方法吗?

Is there any other better way of doing it than

 DecimalFormat df = new DecimalFormat("#.##");

我想要做的基本上是格式双值,如

What i want to do basically is format double values like

23.59004  to 23.59

35.7  to 35.70

3.0 to 3.00

9 to 9.00


推荐答案

不,没有更好的办法。

实际上你的模式有错误。你想要的是:

Actually you have an error in your pattern. What you want is:

DecimalFormat df = new DecimalFormat("#.00"); 

注意00,意思是完全两位小数。

Note the "00", meaning exactly two decimal places.

如果你使用#。##表示可选数字),它将删除尾随零 - 即新的DecimalFormat(#。##)。format(3.0d); 只打印3,而不是3.00

If you use "#.##" (# means "optional" digit), it will drop trailing zeroes - ie new DecimalFormat("#.##").format(3.0d); prints just "3", not "3.00".

这篇关于将Double值格式化为2个小数位的最佳方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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