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

查看:26
本文介绍了将 Double 值格式化为 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?

有没有比

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

我想要做的基本上是像

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.

如果您使用 "#.##"(# 表示可选"数字),它将删除尾随零 - 即 new 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天全站免登陆