Validate/Convert a number using the current Locale()Tag(s): Internationalization String/Number

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
     */
  }
}




If you find this article useful, consider making a small donation
to show your support for this Web site and its content.

Written and compiled by Réal Gagnon ©1998-2012
[ home ]