Search code examples
javaandroiddouble

NumberFormatException: Invalid double: "٢"


After a simple division, I try to round the result to 2 decimal places. Everything works fine, but on some devices, I am getting this symbol "٢" as the result of the division. This symbol then causes a number format exception when I try to round it to 2 decimal places. Can someone explain to me why this is happening, and how I can resolve it

my code:

    double total = 0;
    double average = 0;
    for (HashMap.Entry<String, Double> entry : ratings.entrySet()) {
        String person = entry.getKey();
        Double rating = entry.getValue();
        total += rating;
    }
    average = total / ratings.size();

    ratingsDisplay.setTitleText(roundTo2Decimals(average) + "");

public double roundTo2Decimals(double val) {
    DecimalFormat df2 = new DecimalFormat("###.##");
    return Double.valueOf(df2.format(val)); <== this is where the crash happens
}

Error log:

0java.lang.NumberFormatException: Invalid double: "٢"
1at java.lang.StringToReal.invalidReal(StringToReal.java:63)
2at java.lang.StringToReal.initialParse(StringToReal.java:164)
3at java.lang.StringToReal.parseDouble(StringToReal.java:282)
4at java.lang.Double.parseDouble(Double.java:301)
5at java.lang.Double.valueOf(Double.java:338)
6at com.ducky.flipplanet.ToonViewer.roundTo2Decimals(ToonViewer.java:2750)
7at com.ducky.flipplanet.ToonViewer.calculateAndShowRatings(ToonViewer.java:2919)
8at com.ducky.flipplanet.ToonViewer.loadFromDocId(ToonViewer.java:2850)
9at com.ducky.flipplanet.ToonViewer$79.onDataChange(ToonViewer.java:4816)
10at com.firebase.client.core.ValueEventRegistration.fireEvent(ValueEventRegistration.java:53)
11at com.firebase.client.core.view.DataEvent.fire(DataEvent.java:45)
12at com.firebase.client.core.view.EventRaiser$1.run(EventRaiser.java:38)
13at android.os.Handler.handleCallback(Handler.java:739)
14at android.os.Handler.dispatchMessage(Handler.java:95)
15at android.os.Looper.loop(Looper.java:145)
16at android.app.ActivityThread.main(ActivityThread.java:5938)
17at java.lang.reflect.Method.invoke(Native Method)
18at java.lang.reflect.Method.invoke(Method.java:372)
19at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1400)
20at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1195)

Solution

  • d = Double.parseDouble(new DecimalFormat("####.00").format(d).replace("٠", "0")
                        .replace("١", "1").replace("٢", "2").replace("٣", "3")
                        .replace("٤", "4").replace("٥", "5").replace("٦", "6")
                        .replace("٧", "7").replace("٨", "8").replace("٩", "9")
                        .replace("٫", "."));
    

    // based on Sweeper answer :)