Java 格式设置为两位小数和一个sig fig

Java 格式设置为两位小数和一个sig fig,java,android,Java,Android,我正在尝试将一个double格式化为一个由两位小数和一个sig fig组成的字符串。到目前为止,我的代码如下,我做得对吗?或者我不应该创建一个临时字符串 // sets rounding to two decimal places DecimalFormat format_calculated_reported_concentration = new DecimalFormat("0.00"); // removes grouping seperators e.g. 1,000 becomes

我正在尝试将一个double格式化为一个由两位小数和一个sig fig组成的字符串。到目前为止,我的代码如下,我做得对吗?或者我不应该创建一个临时字符串

// 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));
这不管用吗

// 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一次,而不是每次进行格式化。

请注意,您的变量使用下划线分隔单词,但java惯例是使用大小写。例如,格式“计算的”或“报告的”浓度应改为“计算的报告浓度”。我希望类似于0.006的值变为0.01 2位小数,1 sig fig值的范围是0.005到<0.1。我的意思是,值0.006首先需要四舍五入到两位小数,然后只得到1 sig fig