格式化为两个小数位和1个sig图

时间:2015-02-06 22:06:31

标签: java android

我试图将double格式化为两位小数和1位sig的字符串。到目前为止我的代码在下面,我正确地做了吗?或者我不应该创建一个临时字符串?...

// sets rounding to two decimal places
DecimalFormat format_calculated_reported_concentration = new DecimalFormat("0.00");

// removes grouping seperators e.g. 1,000 becomes 1000
format_calculated_reported_concentration.setGroupingUsed(false);

/// rounds
String temp_calculated_reported_concentration =
       format_calculated_reported_concentration.format(calculated_concentration);

// applies the pattern of 1 significant figure only to the decimalformat
format_calculated_reported_concentration.applyPattern("@");

// 1 sig fig
calculated_reported_concentration = 
       format_calculated_reported_concentration
            .format(Double.valueOf(temp_calculated_reported_concentration));

1 个答案:

答案 0 :(得分:0)

这不会起作用吗?

// sets rounding to two decimal places
DecimalFormat format_calculated_reported_concentration = new DecimalFormat("0.00");

// removes grouping seperators e.g. 1,000 becomes 1000
format_calculated_reported_concentration.setGroupingUsed(false);

// applies the pattern of 1 significant figure only to the decimalformat
format_calculated_reported_concentration.applyPattern("@");

// 1 sig fig
calculated_reported_concentration = 
       format_calculated_reported_concentration
            .format(calculated_concentration);

您也可以设置DecimalFormat一次,就像在构造函数或初始化程序中一样,而不是每次都进行格式化。