Search code examples
javaandroidandroid-5.0-lollipopstring.format

Why String.format("%.2f", 10.0F) returns value 10,00 instead of 10.00?


UPDATE: Removing "in Android 5.0" in the above question as I feel it has nothing to with the version but depends on the locale.

The usual output of the code below is 10.00. But in Android 5.0 it returns value 10,00.

 String value = String.format("%.2f", 10.0F);
 System.out.println("Value is "+value); //For Console Output
 Log.w("NumberClass.java","Value is "+value); //For Logcat Output

Is the functionality of

 String.format("%.2f", 10.0F);

is Changed in android lollipop? If So what is the solution for this strange behaviour?

I need 10.00 as the output.


Solution

  • The doc for String.format() says:

    Returns a localized formatted string, using the supplied format and arguments, using the user's default locale.

    So if you're French, a coma will be used, but if you're american, a dot will be used.

    You may want to use String.format (Locale locale, String format, Object... args) (which is an overload of the function you are currently using) to get the desired behaviour. (see doc here). You can give it an initialized Locale to get the behaviour that you want. For more information on Locale check the documentation here.