后端开发 \ Java \ java保留小数点后几位,不足的用0补

java保留小数点后几位,不足的用0补

总点击459
简介:publicclassTest{ publicstaticvoidmain(String[]args){ Stringresult=Test.roundByScale(2.00,2); System.out.println(result);

public class Test {

public static void main(String[] args) {

String result= Test.roundByScale(2.00,2);

System.out.println(result);

}

public static String roundByScale(double v,int scale) {

if (scale < 0) {

throw new IllegalArgumentException(

"The scale must be a positive integer or zero");

}

if(scale == 0){

return new DecimalFormat("0").format(v);

}

String formatStr = "0.";

for(int i=0;i<scale;i++){

formatStr = formatStr + "0";

}

return new DecimalFormat(formatStr).format(v);

}

}

意见反馈 常见问题 官方微信 返回顶部