2015-02-06 141 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一次,就像在一個構造函數或初始化程序,而不是每次你做的格式化時間。

相關問題