简体   繁体   English

除非有必要使用DecimalFormat,否则如何不显示小数位

[英]How to not display decimal places unless necessary with DecimalFormat

I'm modifying the following code to format doubles: "###,##0.#########". 我正在修改以下代码以格式化双精度格式:“ ###,## 0。#########”。 It generally works the way it should, but when I have a number like "123", it displays it as "123.0". 它通常按应有的方式工作,但是当我有一个类似“ 123”的数字时,它将显示为“ 123.0”。 How do I get it to avoid outputting the decimal place in that case? 在这种情况下,如何避免输出小数位呢? I just want "123" to show up. 我只想显示“ 123”。

After reading the Java tutorial, it seems as though it shouldn't display anything after the decimal place because everything after the decimal place in the formatting string is a pound sign, not a 0. But it's not behaving that way. 阅读Java教程后,似乎它不应显示小数点后的任何内容,因为格式字符串中小数点后的所有内容都是井号,而不是0。但是这种方式并不行。

Also, why is the 0 there in the first place, before the decimal place, in the formatting string? 另外,为什么是摆在首位的0出现,小数位之前 ,在格式化字符串?

Edit: my full code is as follows. 编辑:我的完整代码如下。 I'm new-ish to this project and still trying to figure out why it does this: 我是这个项目的新手,但仍在努力弄清楚为什么这样做:

textField = new TextField("field", Double.class) {
    public org.apache.wicket.util.convert.IConverter getConverter(
            Class type) {
        DoubleConverter converter = (DoubleConverter) DoubleConverter.INSTANCE;
        java.text.NumberFormat numberFormat = converter
                .getNumberFormat(getLocale());
        java.text.DecimalFormat decimalFormat = (java.text.DecimalFormat) numberFormat;
        decimalFormat.applyPattern("###,##0.#########");
        converter.setNumberFormat(getLocale(),
                decimalFormat);
        return converter;
    };
};

The reason you're getting a 0 after the answer, is because you have set the answer to be a double . 答案后得到0的原因是因为您将答案设置为double Doubles are set to be decimal answers. 将双打设置为十进制答案。 If there is nothing there to be a decimal answer, it will automatically place it as a 0, because there must be something after the decimal place. 如果没有小数位答案,它将自动将其设置为0,因为小数位后必须有一些东西。

If you want to get rid of the 0 after the answer, the simplest way would be to change the answer to an integer. 如果要在答案后消除0,最简单的方法是将答案更改为整数。 However using an if statement to check whether it has only one 0 after the decimal place, would allow you to have both an integer answer and a double answer. 但是,使用if语句检查小数点后是否只有一个0,这将使您既有整数答案又有双重答案。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM