将Double值格式化为2个小数位的最佳方法[重复]

本文探讨了如何在Java中将Double值格式化为两位小数。讨论了可能的重复问题,指出使用特定模式进行格式化时需要注意的错误,并提供了两种不同的方法实现:一种使用`DecimalFormat`,另一种使用`String.format()`。
摘要由CSDN通过智能技术生成

本文翻译自:Best way to Format a Double value to 2 Decimal places [duplicate]

This question already has answers here : 这个问题已经在这里有了答案
Closed 7 years ago . 7年前关闭。

Possible Duplicate: 可能重复:
Round a double to 2 significant figures after decimal point 将小数点后的两位有效数字四舍五入

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? 我正在处理应用程序中的许多双精度值,是否有任何简单的方法来处理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 我基本上想做的是格式化double值,例如

23.59004  to 23.59

35.7  to 35.70

3.0 to 3.00

9 to 9.00

#1楼

参考:https://stackoom.com/question/B0rw/将Double值格式化为-个小数位的最佳方法-重复


#2楼

No, there is no better way. 不,没有更好的方法。

Actually you have an error in your pattern. 实际上,您的模式中有一个错误。 What you want is: 您想要的是:

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

Note the "00" , meaning exactly two decimal places. 注意"00"恰好是两个小数位。

If you use "#.##" ( # means "optional" digit), it will drop trailing zeroes - ie new DecimalFormat("#.##").format(3.0d); 如果使用"#.##"#表示“可选”数字),它将删除尾随的零-即new DecimalFormat("#.##").format(3.0d); prints just "3" , not "3.00" . 只打印"3"而不是"3.00"


#3楼

An alternative is to use String.format : 另一种方法是使用String.format

double[] arr = { 23.59004,
    35.7,
    3.0,
    9
};

for ( double dub : arr ) {
  System.out.println( String.format( "%.2f", dub ) );
}

output: 输出:

23.59
35.70
3.00
9.00

You could also use System.out.format (same method signature), or create a java.util.Formatter which works in the same way. 您也可以使用System.out.format (相同的方法签名),或创建一个以相同方式工作的java.util.Formatter

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值