0

I have a double value which needs to be formatted

NumberFormat dft = NumberFormat.getInstance(); 
dft.setMaximumFractionDigits(3);
dft.setRoundingMode(RoundingMode.UP);
Double n= Double.parseDouble(dft.format(xyz)); //1,733.211

I cannot format it because it has "," in it so how to remove it from n.

Maroun
  • 91,013
  • 29
  • 181
  • 233
Shashi Dhar
  • 513
  • 5
  • 7

2 Answers2

1

You need to use parse method of NumberFormat class to parse the number first (if you want to have numeric value), e.g.:

Number number = NumberFormat.getNumberInstance().parse("1,733.211");
System.out.println(number);

Once done, you can format it:

NumberFormat dft = NumberFormat.getInstance(); 
dft.setMaximumFractionDigits(3);
dft.setRoundingMode(RoundingMode.UP);
System.out.println(dft.format(number));
Darshan Mehta
  • 28,982
  • 9
  • 60
  • 90
0

Assuming xyz is a String and you just want to remove the comma:

Double n= Double.parseDouble(dft.format(xyz.replaceAll("[^0-9.]", "")));
Irwan Hendra
  • 150
  • 10
  • The number is a double, not a String. It would be possible, but redundant and only a workaround to convert to a String and then back to a Double. – Austin Schäfer Jul 19 '17 at 08:33
  • thanks i have one more problem , `NumberFormat nft=new DecimalFormat("#0.00"); Double num1= 1.5215897010460924E24;String s1=String.valueOf(num1);Log.printLine(s);//1.5215897010460924E24 Log.printLine(nft.format(Double.parseDouble(s1)));//1521589701046092400000000.00 ` why am i getting such output ? – Shashi Dhar Jul 19 '17 at 13:21
  • they are both equals, the first one is scientific notation format. Have a look at this for some example: https://www.java-tips.org/java-se-tips-100019/34-java-text/2326-display-numbers-in-scientific-notation.html – Irwan Hendra Jul 20 '17 at 05:24