简体   繁体   中英

formating a number/string with decimal separator

I am trying to format a Number with DecimalFormat . But I want it to format a number, that is like

input: 1234.  -->  should be formatted to: 1,234.

But I get 1,234.0 or 1,234.00 depending on my rules for the decimal format What do I have to do in order to get this done?

The methods that should help you are setMinimumFractionDigits and setMaximumFractionDigits .

format.setMinimumFractionDigits(0);

at a guess, is probably what your looking for.


To ensure that the decimal separator is always shown, use: DecimalFormat.setDecimalSeparatorAlwaysShown(true)

You could format the number regardless of whether it is a decimal or not by using

DecimalFormat f = new DecimalFormat("#,###"); 
f.format(whatever)...

If you don't want to display any decimal places, don't format a floating point value :) If you use BigInteger , int , or long , it should be fine:

import java.math.*;
import java.text.*;

public class Test {

    private static final char p = 'p';

    public static void main(String[] args) {
        NumberFormat format = new DecimalFormat();
        BigInteger value = BigInteger.valueOf(1234);
        System.out.println(format.format(value));
        System.out.println(format.format(1234));
        System.out.println(format.format(1234L));
    }
}

Try this:

DecimalFormat df = new DecimalFormat("#,###.", DecimalFormatSymbols.getInstance(Locale.ENGLISH));
System.out.println(df.format(1234));

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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