Tutorial :how to print a Double without commas



Question:

When using toString(), Double adds commas (5143 is printed as 5,143). How to disable the commas?


Solution:1

Your problem belongs to Locale, as pointed out correctly by Rorick. However, you should look into DecimalFormat class, in case changing Locale means mess up all the things.

Look at NumberFormat class, to deal with thousand separator. Because it seems your case is regarding thousand separator instead.


Solution:2

This will remove all grouping (in your case commas).

DecimalFormat df = new DecimalFormat();  df.setGroupingUsed(false);  


Solution:3

As far as I am aware, you can not disable what the toString() method returns.

My solution would be as follows:

someDouble.toString().replaceAll(",", "");  

Not the most elegant solution, but it works.


Solution:4

myDouble.toString().replaceAll(",", "");  


Solution:5

Java has excellent support for formatting numbers in text in different locales with the NumberFormat class:

With current locale:

NumberFormat.getNumberInstance().format(5000000);  

will get you (with swedish locale) the string: 5 000 000

...or with a specific locale (e.g. french, which also results in 5 000 000):

NumberFormat.getNumberInstance(Locale.FRANCE).format(5000000);  


Solution:6

Probably, you have to change your locale settings. It is taken by default from system locale, but you can override this. Read javadoc on Locale class and this little tutorial to start. Locale can be specified through command line:

java -Duser.language=en -Duser.region=US MyApplication  


Solution:7

Three ways:

  1. Using the DecimalFormat

    DecimalFormat df = new DecimalFormat();  DecimalFormatSymbols dfs = df.getDecimalFormatSymbols();  dfs.setGroupingSeparator(Character.MAX_VALUE);  df.setDecimalFormatSymbols(dfs);  System.out.println(df.format(doubleVar));  
  2. (as suggested by others) just replace the comma in the string that you get

  3. Set the locale on load of your VM


Solution:8

NumberFormat format = NumberFormat.getInstance();

format.setGroupingUsed(false);


Solution:9

I use this method to format a double to string with a fixed locale, no grouping and with a minimum and maximum of fraction digits

public String formatNumber(double number){      NumberFormat nf = NumberFormat.getInstance(new Locale("en", "EN"));      nf.setMaximumFractionDigits(3);        nf.setMinimumFractionDigits(1);      nf.setGroupingUsed(false);      String str = nf.format(number);      return str;          }  


Solution:10

Double result= 5143.0;    Sysout(result.toString())   

gives me 5143.0... can u put the code for which u got so


Note:If u also have question or solution just comment us below or mail us on toontricks1994@gmail.com
Previous
Next Post »