how to print a Double without commas

后端 未结 10 719
萌比男神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:20

    NumberFormat format = NumberFormat.getInstance();

    format.setGroupingUsed(false);

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

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

    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.

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

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