本文介绍了Java DecimalFormat的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

我得到0,24

这个问题就是我想把它当作一个双重的。但是Double.valueOf();方法由于逗号在字符串输出中而失败。任何方式解决这个问题?

The problem with this is then I want to use it as a double. But the 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);

我还建议将舍入设置为HALF_UP,因为默认舍入不是我们大多数人期望的: a href =http://docs.oracle.com/javase/1.5.0/docs/api/java/math/BigDecimal.html#ROUND_HALF_EVEN =nofollow> http://docs.oracle.com/ javase / 1.5.0 / docs / api / java / math / BigDecimal.html#ROUND_HALF_EVEN

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

nf.setRoundingMode(RoundingMode.HALF_UP);

这篇关于Java DecimalFormat的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-14 00:38