0

I'm developing an application in Java and found this strange behaviour:

if the regional settings format is set to Hungarian (system default) via the Control Panel, I get this exception, but if I set it to an English one, it works perfectly. Also works on a virtual Mandriva where I'm developing the program in the first place.

This is the code snippet that causes the problem:

public String stattxt(){
    double dt = time_avg();
    double bpm = (Double.compare(dt, 0) == 0) ? 0 : msec2bpm(dt);
    String s = "<html>Number of control points: " + timestamps.size() + "<br>Average dt: " +
        Double.valueOf(new DecimalFormat("#.####").format(dt).toString()) + " ms<br>" +
        "Average BPM: " + Double.valueOf(new DecimalFormat("#.####").format(bpm).toString()) + "<br>&nbsp</html>";
    return s;
}

where both time_avg() and msec2bpm return double (not Double by any chance) values.

How could I make this work regardless to regional settings? Any help would be appreciated.

micha
  • 47,774
  • 16
  • 73
  • 80

3 Answers3

1

It seems like you're using

Double.valueOf(new DecimalFormat("#.####").format(dt).toString())

to round a number to 4 decimal places, but this looks like a hack to me and will fail due to regionalization settings (Hungary probably uses a decimal comma, not a decimal point.)

So, instead round doubles using something like:

rounded = Math.round(original * 10000)/10000.0;

And, if you want to create a string which is a double rounded to 4 decimal places, use String.format()

String.format("%.4f", original);
Ben Braun
  • 418
  • 4
  • 10
  • Since this answer arrived first I tried it instantly and works as expected, thanks! (Can't vote up since I've just registered.) – vizilofaszkalap Dec 23 '12 at 00:05
1

It looks like you should just skip the Double.valueOf:

public String stattxt(){
    double dt = time_avg();
    double bpm = (Double.compare(dt, 0) == 0) ? 0 : msec2bpm(dt);
    String s = "<html>Number of control points: " + timestamps.size() + "<br>Average dt: " +
        new DecimalFormat("#.####").format(dt) + " ms<br>" +
        "Average BPM: " + new DecimalFormat("#.####").format(bpm) + "<br>&nbsp</html>";
    return s;
}
Louis Wasserman
  • 191,574
  • 25
  • 345
  • 413
0

Why are you converting String to Double and then again to String? Do it like this:

public String stattxt(){
    double dt=time_avg();
    double bpm=(Double.compare(dt, 0)==0)?0:msec2bpm(dt);
    String s="<html>Number of control points: "+timestamps.size()+"<br>Average dt: "+
        new DecimalFormat("#.####").format(dt).toString()+" ms<br>"+
                "Average BPM: "+Double.valueOf(new DecimalFormat("#.####").format(bpm).toString())+"<br>&nbsp</html>";
    return s;
}
PrimosK
  • 13,848
  • 10
  • 60
  • 78