Tutorials4u.net Forum
Validate/Convert a number using the current Locale() - Printable Version

+- Tutorials4u.net Forum (http://www.tutorials4u.net/forum)
+-- Forum: Discussion Forum (/forumdisplay.php?fid=1)
+--- Forum: JAVA (/forumdisplay.php?fid=2)
+--- Thread: Validate/Convert a number using the current Locale() (/showthread.php?tid=9)


Validate/Convert a number using the current Locale() - tutorials4u - 12-14-2010 08:37 AM

Depending on the International setting, numbers with comma as decimal separator may be permitted. The NumberFormat class can handle this based on the current Locale().


import java.text.NumberFormat;
import java.text.ParseException;
import java.util.Locale;

public class NumberUtils {

public static double getDoubleValue(String value) throws ParseException {
// use the default locale
return NumberUtils.getDoubleValue(Locale.getDefault(), value);
}

public static double getDoubleValue(Locale loc, String value)
throws ParseException
{
// use the default locale
return NumberFormat.getInstance(loc).parse(value).doubleValue();
}

public static String convertStringAsStringNumberUnLocalized(String value)
throws ParseException
{
// use the default locale
return convertStringAsStringNumberUnLocalized(Locale.getDefault(), value);
}

public static String convertStringAsStringNumberUnLocalized
(Locale loc, String value)
throws ParseException
{
double d = NumberUtils.getDoubleValue(loc, value);
return NumberFormat.getInstance(new Locale("us")).format(d);
}


public static void main(String[] args) throws Exception{

System.out.println(Locale.getDefault());
System.out.println(NumberUtils.getDoubleValue("42,24"));
System.out.println(NumberUtils.getDoubleValue("42.24"));

System.out.println(NumberUtils.convertStringAsStringNumberUnLocalized
(new Locale("fr"), "42,24"));

/*
* output
* fr_CA
* 42.24
* 42.0
* 42.24
*/
}
}