如何在Java中以完全精度格式化double?

时间:2018-01-16 18:56:31

标签: java format double

如何以完全精度格式化双精度?

基本上我想得到那些格式:

FullPrecisionNumericConverter converter =  new FullPrecisionNumericConverter();

Double number = 1234567.8901234567d;  // full precision of double is 17 digits
String amount = converter.toString(number);
String expected = "1,234,567.8901234567"; 
assertEquals(expected, amount);

number = -1234567.8901234567d;
amount = converter.toString(number);
expected = "-1,234,567.8901234567"; 
assertEquals(expected, amount);

number = 12.89;
amount = converter.toString(number);
expected = "12.89"; 
assertEquals(expected, amount);

谢谢!

1 个答案:

答案 0 :(得分:1)

尝试使用DecimalFormat。此代码适用于您提供的特定示例(使用-ea VM选项来检查断言):

import java.math.RoundingMode;
import java.text.DecimalFormat;
import java.text.NumberFormat;

public class Main {

    public static void main(String[] args) {
        DecimalFormat formatter = new DecimalFormat("#,###.##########");

        Double number = new Double(1234567.8901234567d);
        String amount = formatter.format(number);
        System.out.println("amount: " + amount);

        String expected = "1,234,567.8901234567";
        assert(expected.equals(amount));

        number = new Double(-1234567.8901234567d);
        amount = formatter.format(number);
        System.out.println("amount: " + amount);
        expected = "-1,234,567.8901234567";
        assert(expected.equals(amount));

        number = new Double(12.89d);
        amount  = formatter.format(number);
        System.out.println("amount: " + amount);
        expected = "12.89";
        assert(expected.equals(amount));
    }
}