数字格式化在解决实际问题时使用非常普遍,例如保留几位小数,是否分组显示等。
例如求一个圆的面积,用半径作为参数,将结果保留五位小数:
import java.text.DecimalFormat;
public class BubbleSort {
public static void main(String[] args) {
System.out.print("圆的面积为:");
SimpleFormat("#.#####",GetRoundArea(57));
}
public static void SimpleFormat(String str,double value){
DecimalFormat myFormat = new DecimalFormat(str);
// myFormat.setGroupingSize(2);若没有使用“#.#####”约束输出形式,可以使用setGroupingSize()
String output = myFormat.format(value);//将数字进行格式化
System.out.println(output);
}
public static double GetRoundArea(double r){
return Math.PI*Math.pow(r, 2);
}
}