gpt4 book ai didi

java - 使用十进制格式显示前导零

转载 作者:行者123 更新时间:2023-11-30 11:31:57 24 4
gpt4 key购买 nike

我正在尝试使用十进制格式显示小数的前导零...我的代码如下:

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

public class ElementValueUtil {
public static String formatDoubleNonExponential(double value) {
return formatDoubleNonExponential(value, null);
}

public static String formatDoubleNonExponential(double value, String elementName) {
DecimalFormat decimalFormat = new DecimalFormat();

Integer decimalPrecision = 5;
decimalFormat.setMaximumFractionDigits(decimalPrecision);
decimalFormat.setRoundingMode(RoundingMode.HALF_UP);
String exponentialNum = decimalFormat.format(value);
try{
return String.valueOf(decimalFormat.parse(exponentialNum));
}catch(ParseException exception){
return String.valueOf(value);
}
}

public static void main(String[] args) {
Double num = 12.4567012;
System.out.println(formatDoubleNonExponential(num));
}
}

我得到的输出是“12.4567”但我期待“12.45670”

任何帮助将不胜感激...

注意:整数部分可以有任意位数,也可以没有任何数字......但如果小数部分超过 5 位,则小数部分应四舍五入到 5 位小数

For example 
Input Output
12.25 12.25
125.2345 125.2345
12.12340675 12.12341
12.12340123 12.12340

最佳答案

试试这个

static String format(double d) {
String s = new DecimalFormat("").format(d);
if (s.length() - s.indexOf(',') > 5) {
s = String.format("%.5f", d);
}
return s;
}

public static void main(String[] args) throws Exception {
System.out.println(format(12.25));
System.out.println(format(125.2345));
System.out.println(format(12.12340675));
System.out.println(format(12.12340123));
}

输出

12.25
125.2345
12.12341
12.12340

关于java - 使用十进制格式显示前导零,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16935562/

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