1

In android phone this method works fine. It takes any double number and changes to two decimals after dot. But in galaxy tab, number changes to not 0.00, but 0,00. So, when I convert from String to double, I get exception. Why is it acting like that? screenshot

Paulius Vindzigelskis
  • 2,121
  • 6
  • 29
  • 41

2 Answers2

2

Its because of the locality of your tablet, with the locality set on the tablet the numerical seperator is ,, while on other localities (your phone for example) it is ..

You can change the locality using this piece of code:

DecimalFormatSymbols otherSymbols = new DecimalFormatSymbols(Local.GERMAN);
otherSymbols.setDecimalSeparator(',');
otherSymbols.setGroupingSeparator('.'); 
DecimalFormat df = new DecimalFormat(formatString, otherSymbols);

Current local can be gotten using Locale.LOCALITY which can be found in java.util.Local

Here is a workaround for you if you prefer.
Here is a very nice question with related answers (including the one I put here) for you.

Community
  • 1
  • 1
Serdalis
  • 10,296
  • 2
  • 38
  • 58
  • Or just specify a locale which behaves the way you want, of course. – Jon Skeet Apr 24 '12 at 06:28
  • @JonSkeet Yes, but maybe they like where they live :P, this is true though. – Serdalis Apr 24 '12 at 06:30
  • I tried this `String rezS = twoDForm.format(d); if (rezS.contains(",")) { rezS.replace(',', '.'); }`, where I tried to just replace ',' to '.', but it seems don't work. It still returns with ','. I will try changing separator as you mentioned in your code – Paulius Vindzigelskis Apr 24 '12 at 06:32
0

I tried to play with locale and DecimalFormat class and all those separator things, but the problem was not solved. It returned me that false results, which I couldn't parse. So, I hacked it and used Math.round(float), by giving float which contains 100 * d (input), so after round, I divide by those 100 and get two decimals after separator.

public static float roundTwoDecimals(double d) {

    float rez = (float) (d * 100); //multiply for round
    rez = Math.round(rez);
    int rezInt = (int) rez; 
    rez = rezInt; //convert to int to remove unwanted tail
    rez = rez / 100; //get back to two decimals float
    return rez;
}

I think this is not best idea, but it actually works

Paulius Vindzigelskis
  • 2,121
  • 6
  • 29
  • 41
  • This idea is good, but don't know why 123546789 converts to 2147483647. It fails at that point where is `Math.round()` used. Any ideas? – Paulius Vindzigelskis Apr 25 '12 at 11:10
  • Forget this solution. I got back to Serdalis one and changed locale to US (even I am not from here) – Paulius Vindzigelskis Apr 25 '12 at 13:40
  • It's ok, the beauty of it is that it will only change the decimal format symbols and nothing else :D, so the rest of your program will still act as if its in your locality. – Serdalis Apr 25 '12 at 13:44