Question

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

And I get "0,24"

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?

Was it helpful?

Solution

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

nf.setRoundingMode(RoundingMode.HALF_UP);

OTHER TIPS

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 :)

Your problems is the local that your JVM is using , try to change at your current local.

Use DecimalFormat constructor that allows you to specify locale

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. zipf*100 will "cut" off the additional decimal places and zipfLong/100.0 will add the decimal places again. 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.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top