格式,java中双精度小数点后2位,整数小数点后0位
我正在尝试将一个双精度格式设置为精确的小数点后2位,如果它有分数,则使用DecimalFormat将其截断 所以,我想取得下一个成果:格式,java中双精度小数点后2位,整数小数点后0位,java,format,decimal,decimalformat,Java,Format,Decimal,Decimalformat,我正在尝试将一个双精度格式设置为精确的小数点后2位,如果它有分数,则使用DecimalFormat将其截断 所以,我想取得下一个成果: 100.123 -> 100.12 100.12 -> 100.12 100.1 -> 100.10 100 -> 100 变体#1 变体#2 你知道在我的情况下选择什么模式吗?我认为我们需要一个if语句 static double intMargin = 1e-14; public static String myFo
100.123 -> 100.12
100.12 -> 100.12
100.1 -> 100.10
100 -> 100
变体#1
变体#2
你知道在我的情况下选择什么模式吗?我认为我们需要一个if语句
static double intMargin = 1e-14;
public static String myFormat(double d) {
DecimalFormat format;
// is value an integer?
if (Math.abs(d - Math.round(d)) < intMargin) { // close enough
format = new DecimalFormat("#,##0.##");
} else {
format = new DecimalFormat("#,##0.00");
}
return format.format(d);
}
static double intMargin=1e-14;
公共静态字符串myFormat(双d){
十进制格式;
//这个值是整数吗?
如果(Math.abs(d-Math.round(d))
应根据情况选择允许将数字视为整数的裕度。只是不要假设你总是有一个精确的整数,当你期望一个时,double并不总是这样工作的
使用上述声明
myFormat(4)
returns4
,myFormat(4.98)
returns4.98
和myFormat(4.0001)
returns4.00
,我得到的唯一解决方案是使用,如果这里提到了类似的语句:
测试
myFormat(new BigDecimal("100")); // 100
myFormat(new BigDecimal("100.1")); // 100.10
如果有人知道更优雅的方式,请分享 可能的重复我也有一个想法使用if语句,但希望它可以更优雅地解决,使用具有特定模式的DecimalFormat。您可以创建
DecimalFormat
的子类,并将if语句放入子类中。不过,我不确定我是否真的喜欢这个主意。
static double intMargin = 1e-14;
public static String myFormat(double d) {
DecimalFormat format;
// is value an integer?
if (Math.abs(d - Math.round(d)) < intMargin) { // close enough
format = new DecimalFormat("#,##0.##");
} else {
format = new DecimalFormat("#,##0.00");
}
return format.format(d);
}
public static boolean isInteger(BigDecimal bigDecimal) {
int intVal = bigDecimal.intValue();
return bigDecimal.compareTo(new BigDecimal(intVal)) == 0;
}
public static String myFormat(BigDecimal bigDecimal) {
String formatPattern = isInteger(bigDecimal) ? "#,##0" : "#,##0.00";
return new DecimalFormat(formatPattern).format(bigDecimal);
}
myFormat(new BigDecimal("100")); // 100
myFormat(new BigDecimal("100.1")); // 100.10