标签:
1.用DecimalFormat格式化,
DecimalFormat df=new DecimalFormat("0.00");
System.out.println(df.format(1.2));
如果非得要使用double类型呢?
2.
mport java.text.*;
DecimalFormat df=new DecimalFormat(".##");
double d=1252.2563;
String st=df.format(d);
System.out.println(st);
import
java.math.BigDecimal;
import
java.text.DecimalFormat;
import
java.text.NumberFormat;
public
class
format {
double
f =
111231.5585
;
public
void
m1() {
BigDecimal bg =
new
BigDecimal(f);
double
f1 = bg.setScale(
2
, BigDecimal.ROUND_HALF_UP).doubleValue();
System.out.println(f1);
}
/**
* DecimalFormat转换最简便
*/
public
void
m2() {
DecimalFormat df =
new
DecimalFormat(
"#.00"
);
System.out.println(df.format(f));
}
/**
* String.format打印最简便
*/
public
void
m3() {
System.out.println(String.format(
"%.2f"
, f));
}
public
void
m4() {
NumberFormat nf = NumberFormat.getNumberInstance();
nf.setMaximumFractionDigits(
2
);
System.out.println(nf.format(f));
}
public
static
void
main(String[] args) {
format f =
new
format();
f.m1();
f.m2();
f.m3();
f.m4();
}
}
import java.text.NumberFormat;
public class TestNumberFormat {
public static void main(String[] args) {
NumberFormat nf = NumberFormat.getInstance();
nf.setMaximumFractionDigits(2);
double var = 8.88888;
System.out.println(nf.format(var));
}
}
java double保留小数点的零的问题,java保留小数点问题
标签:
原文地址:http://www.cnblogs.com/tian830937/p/4424867.html