how to print a Double without commas

后端 未结 10 718
萌比男神i
萌比男神i 2020-12-11 15:37

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

相关标签:
10条回答
  • 2020-12-11 16:06

    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
    0 讨论(0)
  • 2020-12-11 16:09

    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.

    0 讨论(0)
  • 2020-12-11 16:12

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

    DecimalFormat df = new DecimalFormat();
    df.setGroupingUsed(false);
    
    0 讨论(0)
  • 2020-12-11 16:16
    myDouble.toString().replaceAll(",", "");
    
    0 讨论(0)
  • Double result= 5143.0;
    
    Sysout(result.toString()) 
    

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

    0 讨论(0)
  • 2020-12-11 16:18

    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);
    
    0 讨论(0)
提交回复
热议问题