2015-02-06 103 views
1

我试图将一个double格式化为两位小数和1位sig字符串。我的代码到目前为止,我是否正确地做?或者我不应该创建一个临时字符串?...格式化为小数点后两位和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

请注意,您的变量使用下划线来分隔单词,但Java约定是使用camelCase。例如,'format_calculated_reported_concentration'应该是'formatCalculatedReportedConcentration'。 – 2015-02-06 22:11:27

+0

我希望像0.006这样的东西变成0.01(2位小数,1 sig图) – 2015-02-06 22:23:04

+0

值的范围是0.005到<0.1 – 2015-02-06 22:24:22

回答

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一次,就像在一个构造函数或初始化程序,而不是每次你做的格式化时间。

相关问题