如何在 Java 中格式化数字? [英] How do I format a number in Java?

查看:35
本文介绍了如何在 Java 中格式化数字?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何在 Java 中格式化数字?
什么是最佳实践"?

How do I format a number in Java?
What are the "Best Practices"?

在格式化之前是否需要舍入数字?

Will I need to round a number before I format it?

32.302342342342343 =>32.30

.7323 =>0.73

推荐答案

来自这个话题,有不同的方法可以做到这一点:

From this thread, there are different ways to do this:

double r = 5.1234;
System.out.println(r); // r is 5.1234

int decimalPlaces = 2;
BigDecimal bd = new BigDecimal(r);

// setScale is immutable
bd = bd.setScale(decimalPlaces, BigDecimal.ROUND_HALF_UP);
r = bd.doubleValue();

System.out.println(r); // r is 5.12

<小时>

f = (float) (Math.round(n*100.0f)/100.0f);

<小时>

DecimalFormat df2 = new DecimalFormat( "#,###,###,##0.00" );
double dd = 100.2397;
double dd2dec = new Double(df2.format(dd)).doubleValue();

// The value of dd2dec will be 100.24

DecimalFormat() 似乎是最有活力的方式,看别人的代码也很容易理解.

The DecimalFormat() seems to be the most dynamic way to do it, and it is also very easy to understand when reading others code.

这篇关于如何在 Java 中格式化数字?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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