四舍五入至某小数位后返回数字串
/**
將數字四捨五入至某小數位, 並返回指定位數字串
function2(123.455,2) => 123.46
function2(123.449,2) => 123.45
function2(123.44,3) => 123.440
function2(123.4455,3) => 123.446
function2(123.4499,3) => 123.450
function2(123.9,0) => 124
程式接口:
public static double function2(double value,int decimalPlaces); */
將數字四捨五入至某小數位, 並返回指定位數字串
function2(123.455,2) => 123.46
function2(123.449,2) => 123.45
function2(123.44,3) => 123.440
function2(123.4455,3) => 123.446
function2(123.4499,3) => 123.450
function2(123.9,0) => 124
程式接口:
public static double function2(double value,int decimalPlaces); */
public static double function2(double value,int decimalPlaces){
double dbl = value*(Math.pow(10, decimalPlaces+1) );
Double d = new Double(dbl);
int intValue = d.intValue();
intValue+=5; //四舍五入关键步骤
intValue = intValue/10; //舍弃最后一位
int value1 = intValue /((int)Math.pow(10, decimalPlaces));
int value2 = intValue % ((int)Math.pow(10, decimalPlaces));
String str = value1+"."+value2;
if(decimalPlaces==0)str = value1+"";
System.out.println("str = "+str);
return Double.parseDouble(str);
}
---------------------------纵横软件邮件所发笔试题2