Java 使用 DecimalFormat 的问题

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/3735630/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-14 04:05:36  来源:igfitidea点击:

Problems using DecimalFormat

javadecimalformat

提问by Lars

I am having problems using DecimalFormatwhen I am going to print out coefficients after a regression.

DecimalFormat在回归后打印系数时遇到问题。

Here is the part of the code that is facing problems;

这是代码中遇到问题的部分;

DecimalFormat twoDForm = new DecimalFormat("0.00");   
private double s(double d){  
    return Double.valueOf(twoDForm.format(d));  
}  

and here is the error message in eclipse;

这是eclipse中的错误信息;

Exception in thread "main" java.lang.NumberFormatException: For input string: "0,16"  
 at sun.misc.FloatingDecimal.readJavaFormatString(Unknown Source)  
 at java.lang.Double.valueOf(Unknown Source)  
 at model.ARF2.s(ARF2.java:126)  
 at model.ARF2.printBestModel(ARF2.java:114)  
 at testing.testclass3.bestForecastingModel(testclass3.java:69)  
 at testing.testclass3.main(testclass3.java:36)  

Please let me know if anyone has any surgestions on how to fix the code. I want two decimals on my coefficients.

如果有人对如何修复代码有任何疑问,请告诉我。我的系数要两位小数。

Thank you

谢谢

Lars

拉斯

回答by Thomas Langston

http://download.oracle.com/javase/1.4.2/docs/api/java/text/DecimalFormat.html

http://download.oracle.com/javase/1.4.2/docs/api/java/text/DecimalFormat.html

The following excerpt appears to be part of your problem:

以下摘录似乎是您的问题的一部分:

To obtain a NumberFormat for a specific locale, including the default locale, call one of NumberFormat's factory methods, such as getInstance(). In general, do not call the DecimalFormat constructors directly, since the NumberFormat factory methods may return subclasses other than DecimalFormat. If you need to customize the format object, do something like this:

要获取特定语言环境(包括默认语言环境)的 NumberFormat,请调用 NumberFormat 的工厂方法之一,例如 getInstance()。通常,不要直接调用 DecimalFormat 构造函数,因为 NumberFormat 工厂方法可能返回 DecimalFormat 以外的子类。如果您需要自定义格式对象,请执行以下操作:

 NumberFormat f = NumberFormat.getInstance(loc);
 if (f instanceof DecimalFormat) {
     ((DecimalFormat) f).setDecimalSeparatorAlwaysShown(true);
 }

You may want to use the applyPattern method:

您可能想要使用 applyPattern 方法:

applyPattern

public void applyPattern(String pattern) Apply the given pattern to this Format object. A pattern is a short-hand specification for the various formatting properties. These properties can also be changed individually through the various setter methods. There is no limit to integer digits are set by this routine, since that is the typical end-user desire; use setMaximumInteger if you want to set a real value. For negative numbers, use a second pattern, separated by a semicolon

Example "#,#00.0#" -> 1,234.56

This means a minimum of 2 integer digits, 1 fraction digit, and a maximum of 2 fraction digits.

Example: "#,#00.0#;(#,#00.0#)" for negatives in parentheses.

In negative patterns, the minimum and maximum counts are ignored; these are presumed to be set in the positive pattern.

Throws: NullPointerException - if pattern is null IllegalArgumentException - if the given pattern is invalid.

应用模式

public void applyPattern(String pattern) 将给定的模式应用于此 Format 对象。模式是各种格式属性的简写规范。这些属性也可以通过各种 setter 方法单独更改。此例程设置的整数位数没有限制,因为这是典型的最终用户期望;如果要设置实际值,请使用 setMaximumInteger。对于负数,使用第二个模式,用分号分隔

示例 "#,#00.0#" -> 1,234.56

这意味着最少 2 个整数,1 个小数位,最多 2 个小数位。

示例:“#,#00.0#;(#,#00.0#)”用于括号中的否定。

在负模式中,最小和最大计数被忽略;这些被假定为正模式。

抛出: NullPointerException - 如果模式为 null IllegalArgumentException - 如果给定的模式无效。

回答by Hyman Leow

Are you trying to format the number? Or round it? If you're formatting it, shouldn't your "s" method (bad name IMO, btw, but it's private, so it's your call) return a java.lang.Stringinstead of a double?

你想格式化数字吗?还是圆呢?如果您要格式化它,您的“s”方法(IMO 名称不好,顺便说一句,但它是私有的,因此是您的调用)不应该返回 ajava.lang.String而不是 adouble吗?

回答by nanda

I think what you intended to do is:

我认为你打算做的是:

private static String s(double d) {
   return twoDForm.format(d);
}

回答by Devon_C_Miller

You are encountering an i18n issue. DecimalFormatis using your default locale which specifies the decimal separator as ,. However, the Double.valueOfdoes not use the locale. It always expects that the decimal separator is ..

您遇到了 i18n 问题。DecimalFormat正在使用您的默认语言环境,它将小数点分隔符指定为,. 但是,Double.valueOf不使用语言环境。它总是期望小数点分隔符是..

If you want to parse a string formatted with DecimalFormatthen you need to use DecimalFormat.parse

如果要解析格式化的字符串,DecimalFormat则需要使用DecimalFormat.parse

回答by Miky

use:

用:

    DecimalFormat twoDForm = new DecimalFormat("#.##");
    DecimalFormatSymbols dfs = new DecimalFormatSymbols();
    dfs.setDecimalSeparator('.');
    twoDForm.setDecimalFormatSymbols(dfs);

回答by Mohamed Hisham Ibn Hanifa

Check your Locale.

检查您的语言环境。

DecimalFormat twoDForm = new DecimalFormat("0.00");   
    private double s(double d){ 

    String doubleString =  displayNumberAmount(twoDForm.format(d));
        return Double.valueOf(doubleString);  
    } 

    public static String displayNumberAmount(String amount) {

            NumberFormat numberFormat = NumberFormat.getNumberInstance(Locale.CANADA_FRENCH);

            Number number = 0;

            try {
                number = numberFormat.parse(amount);

            } catch (ParseException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }

            return String.format(Locale.US, "%1$,.2f", number);
        }