How to Convert a String to Double in Java Using a Specific Locale

How do I convert a String to Double in Java using a specific locale?

Try java.text.NumberFormat. From the Javadocs:

To format a number for a different Locale, specify it in the call to getInstance.

NumberFormat nf = NumberFormat.getInstance(Locale.FRENCH);

You can also use a NumberFormat to parse numbers:

myNumber = nf.parse(myString);

parse() returns a Number; so to get a double, you must call myNumber.doubleValue():

    double myNumber = nf.parse(myString).doubleValue();

Note that parse() will never return null, so this cannot cause a NullPointerException. Instead, parse throws a checked ParseException if it fails.

Edit: I originally said that there was another way to convert to double: cast the result to Double and use unboxing. I thought that since a general-purpose instance of NumberFormat was being used (per the Javadocs for getInstance), it would always return a Double. But DJClayworth points out that the Javadocs for parse(String, ParsePosition) (which is called by parse(String)) say that a Long is returned if possible. Therefore, casting the result to Double is unsafe and should not be tried!

Thanks, DJClayworth!

How do I convert a String to Double in GWT using a specific locale?

Try adding <meta name='gwt:property' content='locale=sl_SI' /> to the html host page

Here's an explanation on why it works like this: https://stackoverflow.com/a/16295300/572830

Here's the broader and detailed explanation: https://developers.google.com/web-toolkit/doc/latest/DevGuideI18nLocale

Convert a String to Double - Java

Have a look at java.text.NumberFormat. For example:

import java.text.*;
import java.util.*;

public class Test
{
// Just for the sake of a simple test program!
public static void main(String[] args) throws Exception
{
NumberFormat format = NumberFormat.getInstance(Locale.US);

Number number = format.parse("835,111.2");
System.out.println(number); // or use number.doubleValue()
}
}

Depending on what kind of quantity you're using though, you might want to parse to a BigDecimal instead. The easiest way of doing that is probably:

BigDecimal value = new BigDecimal(str.replace(",", ""));

or use a DecimalFormat with setParseBigDecimal(true):

DecimalFormat format = (DecimalFormat) NumberFormat.getInstance(Locale.US);
format.setParseBigDecimal(true);
BigDecimal number = (BigDecimal) format.parse("835,111.2");

Locale independent String to double

From the looks of it, the correct way to do it is:

public double stringToDouble(String s){
if (nf == null){
nf = NumberFormat.getInstance(Locale.getDefault());
}
try {
return nf.parse(s).doubleValue();
} catch (ParseException e) {
e.printStackTrace();
return 0.0;
}
}

So far that seems to be working for me.

How to get Double from String based on locale?

I found a solution that helped me in my case:

public double getDoubleFromString(String string) {
NumberFormat format = NumberFormat.getInstance(Locale.getDefault());
Number number;
double d;
try {
number = format.parse(string);
d = number.doubleValue();
} catch (Exception e) {
e.printStackTrace();
d = Double.NaN;
}
return d;
}

This is what I meant and looked for. Maybe someone will come in handy.

How to convert a String to another locale?

I suggest you have a ten digit lookup String and replace all the digits one at a time.

public static void main(String... args) {
System.out.println(arabicToDecimal("۴۲"));
}
//used in Persian apps
private static final String extendedArabic = "\u06f0\u06f1\u06f2\u06f3\u06f4\u06f5\u06f6\u06f7\u06f8\u06f9";

//used in Arabic apps
private static final String arabic = "\u0660\u0661\u0662\u0663\u0664\u0665\u0666\u0667\u0668\u0669";

private static String arabicToDecimal(String number) {
char[] chars = new char[number.length()];
for(int i=0;i<number.length();i++) {
char ch = number.charAt(i);
if (ch >= 0x0660 && ch <= 0x0669)
ch -= 0x0660 - '0';
else if (ch >= 0x06f0 && ch <= 0x06F9)
ch -= 0x06f0 - '0';
chars[i] = ch;
}
return new String(chars);
}

prints

42

The reason for using the strings as a lookup is that other characters such as . - , would be left as is. In fact a decimal number would be unchanged.

How to convert String to Double correctly?

In your case, is not just a "number", is a currency.

A simple way to deal with it is to convert into a number and parse:

String t = "1.000,00";
// the order of replaces here is important
String formated = t.replace(".", "").replace(",", ".");

userIncome = Double.valueOf(formated);

But, if your application is focus on currency you should take a look in this:
https://www.baeldung.com/java-money-and-currency

Convert a DoubleValue as String to Number using NumberFormat

NumberFormat.getInstance();

Will get an Instance of NumberFormat for the current default FORMAT locale of the JVM the program is running in.

Not every locale format uses dot as a decimal sign. Guessing by your name you are probably having german as a default locale and therefor comma is used as the decimal sign while dot is interpreted as a simple (thousands) separator that is used to make numbers more human readable.

To get a NumberFormat instance that ignores the current default locale you can use:

NumberFormat.getInstance(Locale.ROOT);

How to change a double to a string

You already get the value rounded as you want and as a string from the formatter. Don't try to parse it, just display it.

BMIResult.setText(df.format(BMI));


Related Topics



Leave a reply



Submit