127

I currently use the following code to print a double:

return String.format("%.2f", someDouble);

This works well, except that Java uses my Locale's decimal separator (a comma) while I would like to use a point. Is there an easy way to do this?

dtech
  • 13,741
  • 11
  • 48
  • 73
  • If you need using the double value with precise decimals, maybe you should use BigDecimal instead of double/Double. See this [link](http://stackoverflow.com/questions/15625556/java-adding-and-subtracting-doubles-are-giving-strange-results) for issues you may encounter when using double variables. You can also try this: System.out.println(5.1d + 1.1d); - the result will be 6.199999999999999 instead of 6.2. I think that somebody looking on how to format numbers with decimals as String must skip double variables. – razvanone Oct 13 '16 at 10:01

7 Answers7

208

Use the overload of String.format which lets you specify the locale:

return String.format(Locale.ROOT, "%.2f", someDouble);

If you're only formatting a number - as you are here - then using NumberFormat would probably be more appropriate. But if you need the rest of the formatting capabilities of String.format, this should work fine.

Jon Skeet
  • 1,421,763
  • 867
  • 9,128
  • 9,194
  • 6
    Locale.ROOT is more neutral. – speedogoo Jun 17 '16 at 08:03
  • @speedogoo: Edited, although I suspect for number formatting it doesn't make any difference. – Jon Skeet Jun 17 '16 at 08:17
  • 1
    Yeah, but you don't need to choose between US and UK. – speedogoo Jun 17 '16 at 08:43
  • 2
    Locale.ROOT is also safe against possible future changes in a country's choice of decimal separator. – Attila Tanyi Oct 17 '16 at 09:58
  • IMO this does not answer the question, rather the Locale.setDefault(new Locale("en", "US")); does as pointed out in an other answer. True that maybe have undesirable side effects as it is global, OTH as programmer what I really want is that the global default is US because everywhere else in my code where I do care about locale I do that explicitly. – nyholku Jan 08 '19 at 13:30
  • @nyholku: I think it answers the question as asked, to be honest. Setting the default and then relying on it can be risky - anything else could then set the default to something else. I prefer to be explicit everywhere it matters (just as I do with encodings, and time zones). Sure, there are multiple ways of achieving the goal of formatting a value using a specific locale - but the answer here *is* one of them, even if it's not the one you prefer. – Jon Skeet Jan 08 '19 at 13:38
  • Well IMO strictly speaking it does not answer the question.The way I read the question is "how to make Java use point as a decimal separator". The question is/was not "how to modify my code to make my code use point as decimal separator". It is good to know about the possible risks and inform the readers about it ... OTH any production code that relies on the default is faulty anyway as I just found out when I upgraded a project from Java 7 to Java 11 and uncovered that the default was changed at some point. – nyholku Jan 08 '19 at 14:45
  • @nyholku: I think we'll have to agree to disagree at this point. The original asker was clearly happy enough that it answered *their* question to accept the answer. It may not be the answer *you* prefer, but that's a different matter. – Jon Skeet Jan 08 '19 at 15:23
  • I'm happy to disagree on this. I also disagree with your implied assessment that my preferences is clouding my objectivity as to weather this answers the question or not. The fact that the original asker is happy is IMO not an indication that the answer answers the question. A case in point: the IMO right answer was posted three weeks after the accepted answer so it did not enter the beauty contest. To make a correct assessment as to weather the question and answer match we must look only at the text of the question and answer and nothing else. – nyholku Jan 08 '19 at 15:50
24

A more drastic solution is to set your Locale early in the main().

Like:

Locale.setDefault(new Locale("en", "US"));
Federico Giorgi
  • 10,495
  • 9
  • 42
  • 56
  • 18
    This is a _very_ problematic answer, because it has a global effect, thus may cause a lot of other (possibly undesirable) changes. – sleske Feb 25 '16 at 14:12
  • 5
    IMO this is the correct answer to the question and beside as programmer this is what I want. I want Java to use US locale by default as everywhere in my code where I actually need localisation I will make it explicit in my code. Just my habits perhaps but it is very annoying when printf/format uses my local Locale cause then the decimal 'comma' is totally incompatible with other software (Matlab anyone) that I use. – nyholku Jan 08 '19 at 13:33
17

Way too late but as other mentioned here is sample usage of NumberFormat (and its subclass DecimalFormat)

public static String format(double num) {
    DecimalFormatSymbols decimalSymbols = DecimalFormatSymbols.getInstance();
    decimalSymbols.setDecimalSeparator('.');
    return new DecimalFormat("0.00", decimalSymbols).format(num);
 }
VizGhar
  • 3,036
  • 1
  • 25
  • 38
  • 1
    I have a feeling that creating `DecimalFormatSymbols` and setting the separator should be done once, before this method. – Line Feb 22 '19 at 21:22
13

You can pass an additional Locale to java.lang.String.format as well as to java.io.PrintStream.printf (e.g. System.out.printf()):

import java.util.Locale;

public class PrintfLocales {

    public static void main(String args[]) {
        System.out.printf("%.2f: Default locale\n", 3.1415926535);
        System.out.printf(Locale.GERMANY, "%.2f: Germany locale\n", 3.1415926535);
        System.out.printf(Locale.US, "%.2f: US locale\n", 3.1415926535);
    }

}

This results in the following (on my PC):

$ java PrintfLocales
3.14: Default locale
3,14: Germany locale
3.14: US locale

See String.format in the Java API.

Simon A. Eugster
  • 4,114
  • 4
  • 36
  • 31
  • 4
    You can also use `out.printf((Locale)null, ...)` or `out.format((Locale)null, ...)` to get a locale independent representation. (and there is also [`Locale.ROOT`](http://docs.oracle.com/javase/6/docs/api/java/util/Locale.html#ROOT)) – eckes Jan 19 '13 at 03:40
0

You can use NumberFormat and DecimalFormat.

Take a look at this link from Java Tutorials LocaleSpecific Formatting

The section titled Locale-Sensitive Formatting is what you need.

blong824
  • 3,920
  • 14
  • 54
  • 75
-4

Change the language, it worked for me.

How to set eclipse console locale/language How to set eclipse console locale/language

-5

I had the same issue.. 55.1 transformed to 55,10. My quick (dirty?) fix is :

String.format("%.2f", value).replaceAll(",",".");

cjnash
  • 1,228
  • 3
  • 19
  • 37
fred'
  • 1
  • 2