Search code examples
javaandroidstring-conversion

format float[] to String decimal sign changes to comma


float[] to string

When I try to convert a float array value to a string the sign changes to comma?

    private float[] myNum = {0.06f, 0.07f, 0.08f};
    

Case 1:

    String myString = String.format("%.2f", myNum[0]);

In Case1 myString is "0,06"

Case 2:

    String myString = "" + myNum[0];

In Case 2 myString is "0.06"

I do not understand why this is happening. All help is much appreciated.


Solution

  • That is because String.format() is locale-aware. I'm guessing your default locale is Locale.GERMAN, since Locale.NORWEGIAN does not exist. And the decimal separator is a comma.

    The locale always used is the one returned by Locale.getDefault().

    If you want to format according to a specific locale, then you should use

    Locale myLocale = ...;
    String.format(myLocale, "%.2f", myNum[0]);
    

    The Java Virtual Machine sets the default locale during startup based on the host environment. It is used by many locale-sensitive methods if no locale is explicitly specified. It can be changed using the setDefault method. You can easily check your locale: System.out.println(Locale.getDefault()).