gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-02 11:44:48 25 4
gpt4 key购买 nike

如何以全精度格式化 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);

谢谢!

最佳答案

尝试十进制格式。此代码适用于您提供的特定示例(使用 -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));
}
}

关于java - 如何在Java中以全精度格式化 double ?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48288050/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com