简体   繁体   English

Java DecimalFormat

[英]Java DecimalFormat

 DecimalFormat df2 = new DecimalFormat("#.##");
double zipf = 0.23951367781155017; 
String zipt = df2.format(zipf);
System.out.println(zipt);

And I get "0,24" 我得到“ 0,24”

The problem with this is then I want to use it as a double. 问题是我想将它用作双精度型。 But the Double.valueOf(); 但是Double.valueOf(); method fails due to the comma being there in the string output. 方法失败,因为字符串输出中有逗号。 Any way to solve this? 有什么办法解决这个问题?

For decimal dot, you should create an instance with english locale like this: 对于小数点,您应该使用英语语言环境创建一个实例,如下所示:

NumberFormat nf = NumberFormat.getNumberInstance(Locale.ENGLISH);
nf.setMinimumFractionDigits(2);
nf.setMaximumFractionDigits(2);
String zipt = nf.format(zipf);
System.out.println(zipt);

I also suggest setting rounding to HALF_UP, because default rounding is not what most of us would expect: http://docs.oracle.com/javase/1.5.0/docs/api/java/math/BigDecimal.html#ROUND_HALF_EVEN 我还建议将舍入设置为HALF_UP,因为默认舍入不是我们大多数人期望的: http ://docs.oracle.com/javase/1.5.0/docs/api/java/math/BigDecimal.html#ROUND_HALF_EVEN

nf.setRoundingMode(RoundingMode.HALF_UP);

Use different locale.German has dot 使用不同的语言环境。

NumberFormat nf = NumberFormat.getNumberInstance(Locale.GERMAN);
DecimalFormat df = (DecimalFormat)nf;

Alternative woud be to use string and then modify string to your needs.After that just parse to double.All done :) 另一种方法是使用字符串,然后根据需要修改字符串,之后只需将其解析为两倍即可。

您的问题是您的JVM使用的本地,尝试在您当前的本地更改。

使用DecimalFormat构造函数,该构造函数允许您指定区域设置

new DecimalFormat("#.##", new DecimalFormatSymbols(new Locale("en")));

you could "format" your double manually but cutting of the decimal places like this: 您可以手动“格式化”双精度型,但可以像这样切割小数位:

DecimalFormat df2 = new DecimalFormat("#.##");
double zipf = 0.23951367781155017;
String zipt = df2.format(zipf);
System.out.println(zipt);

long zipfLong = Math.round(zipf*100);
double zipfDouble = zipfLong/100.0;
System.out.println(zipfDouble);

with Math.round you make sure the that 0.239.. becomes 0.24. 使用Math.round时,请确保0.239 ..变为0.24。 zipf*100 will "cut" off the additional decimal places and zipfLong/100.0 will add the decimal places again. zipf*100将“切除”其他小数位,而zipfLong/100.0将再次添加小数位。 Sorry, bad explanation but here is the output: 抱歉,不好的解释,但这是输出:

0,24
0.24

And you can reuse the new zipfDouble as a double value without casting or taking care of locale settings. 而且,您可以将新的zipfDouble用作double值,而无需强制转换或注意locale设置。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM