Taglocale

Localized vs locale-independent double

Sometimes we need to have double converted to string in specific format. For example, when this data will be used in system level rather than displayed to user.

Let’s say, we need to send double to server in format like X.XX

The easiest (wrong) way to do this, for example:

String formattedDouble = String.format("%.2f", 0.01f);

Expecting to see “0.01” as output. But actually it will be converted using phone default locale.

On most locales this will work and nobody will notice the difference. However if your default locale is, for example, Russian, decimal delimeter for it is “,” opposing to “.”

In this case we will get “0,01” and the server will return error (evil laugh here) as it expects “.” as delimiter.

So we want to avoid any unexpected locale-specific formatting. We can use US locale to get expected results.

String formattedDouble = String.format(Locale.US, "%.2f", 0.01f)

This will return “0.01” and server will be happy.

Another way is to use DecimalFormat for advanced formatting.

Again, be aware of default locale, doing this:

DecimalFormat decimalFormat = new DecimalFormat("0.00");
String formattedDouble = decimalFormat.format(0.01f);

could result “0,01” if default locale is Russian.

//Anton

“Loaded time zone names for” during XML parse

Do not use java.util.Date object in XML parse! Because if you once change locale in your phone settings – XML.parse() could take couple minutes.

You will see

I/Resources( 1088): Loaded time zone names for en_uk in 1764ms.

in your DDMS log as well as huge gc() work.

© 2017 Android Tales

Theme by Anders NorenUp ↑