开发者

Java: Float Formatting depends on Locale [duplicate]

This question already has answers here: Force point (".") as decimal separator in java (7 answers) Closed 7 years ago.

I live in开发者_如何学Go Belgium. And generally, in mathematics, we write our decimals with a comma like this: 3,141592

And that is also the result when I format the float.

System.out.println(String.format("%f", 3.141592));

So, the . is replaced by a , like so: 3,141592. So always when I need a point instead I have to add something like this: String.format("%f", 3.14).replace(',','.');

So, the question is: is there a way to change the Locale which makes every formatter in Java use a point, instead of comma?

Thanks


System.out.println(Locale.getDefault());

prints

nl_BE


Try using String.format(Locale.US, "%f", floatValue) for just setting locale used during formatting.


A simple solution, but would be wide reaching across the entire Locale, would be to set the system Locale to US or UK. Example.

Locale.setDefault(Locale.US);

Since you have changed the question, then you simply specify the local with your print method.

System.out.println(String.format(Locale.US, "%f", 3.141592));


It may be useful to look at http://download.oracle.com/javase/6/docs/api/java/text/DecimalFormat.html which contains a number of options for precise output of strings using Locale where necessary

DecimalFormat is a concrete subclass of NumberFormat that formats decimal numbers. It has a variety of features designed to make it possible to parse and format numbers in any locale, including support for Western, Arabic, and Indic digits. It also supports different kinds of numbers, including integers (123), fixed-point numbers (123.4), scientific notation (1.23E4), percentages (12%), and currency amounts ($123). All of these can be localized.

It is often useful to route input and output through bespoke routines. Here is one from the JAMA library (http://math.nist.gov/javanumerics/jama/)

   public void print (PrintWriter output, int w, int d) {
      DecimalFormat format = new DecimalFormat();
      format.setDecimalFormatSymbols(new DecimalFormatSymbols(Locale.US));
      format.setMinimumIntegerDigits(1);
      format.setMaximumFractionDigits(d);
      format.setMinimumFractionDigits(d);
      format.setGroupingUsed(false);
      print(output,format,w+2);
   }

By using this you can be sure that future problems and enhancements are likely to be addressed


For formatting numbers, you really should not rely on toString(). Use String.format(), the factory methods in NumberFormat, or DecimalFormat, which allow you to control how numbers are formatted (the first two by choosing a Locale) without relying on some global setting.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜