user3346857
user3346857

Reputation: 25

Java DecimalFormat

 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?

Upvotes: 0

Views: 1996

Answers (5)

GameDroids
GameDroids

Reputation: 5662

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.

Upvotes: 0

endriu_l
endriu_l

Reputation: 1659

Use DecimalFormat constructor that allows you to specify locale

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

Upvotes: 0

Makoton
Makoton

Reputation: 453

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

Upvotes: 0

NeplatnyUdaj
NeplatnyUdaj

Reputation: 6242

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

Upvotes: 1

Tomas Bisciak
Tomas Bisciak

Reputation: 2841

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

Upvotes: 0

Related Questions