Post Reply 
 
Thread Rating:
  • 1 Votes - 4 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Validate/Convert a number using the current Locale()
12-14-2010, 08:37 AM
Post: #1
Validate/Convert a number using the current Locale()
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
*/
}
}
Find all posts by this user
Quote this message in a reply
Post Reply 


Forum Jump:



Send your comments, Suggestions or Queries regarding this site at info@tutorials4u.net

Copyright © 2010 Tutorials4u.net All Rights Reserved