gpt4 book ai didi

Java转换一个format.String

转载 作者:塔克拉玛干 更新时间:2023-11-01 22:22:29 24 4
gpt4 key购买 nike

我还是 Java 的新手,我想知道是否有任何方法可以在不四舍五入的情况下将其格式化为 double ?示例:

double n = 0.12876543;
String s = String.format("%1$1.2f", n);

如果我要打印到系统,它会返回 0.13 而不是精确的 0.12。现在我想到了一个解决方案,但我想知道是否有更好的方法来做到这一点。这是我的简单解决方案:

double n = 0.12876543;
double n = Double.parseDouble(String.format(("%1$1.2f", n));

还有其他想法或解决方案吗?

最佳答案

一个优雅的解决方案是使用 setRoundingModeDecimalFormat。它适本地设置了 RoundingMode

例如:

// Your decimal value
double n = 0.12876543;
// Decimal Formatting
DecimalFormat curDf = new DecimalFormat(".00");
// This will set the RoundingMode
curDf.setRoundingMode(RoundingMode.DOWN);
// Print statement
System.out.println(curDf.format(n));

输出:

0.12

此外,如果您想将额外的格式设置为字符串,您可以随时将 double 值更改为字符串:

// Your decimal value
double n = 0.12876543;
// Decimal Formatting
DecimalFormat curDf = new DecimalFormat(".00");
// This will set the RoundingMode
curDf.setRoundingMode(RoundingMode.DOWN);
// Convert to string for any additional formatting
String curString = String.valueOf(curDf.format(n));
// Print statement
System.out.println(curString);

输出:

0.12

请在此处引用类似的解决方案:https://stackoverflow.com/a/8560708/4085019

关于Java转换一个format.String,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40306355/

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