2012-01-17 532 views
1

我想轉換兩個精度的雙值。 假設double s = 1.3333333及其答案就像使用java.text.DecimalFormat中如何轉換黑莓中的雙精度雙精度?

double s = 1.4454644567; 
DecimalFormat df = new DecimalFormat("#.##"); 
System.out.println(df.format(d)); 

但不是在這個黑莓s = 1.33

這樣做是在java中。

+0

你準備後作出的計算,或者你只想打印或某處顯示呢? – 2012-01-17 07:10:58

+0

@EugenMartynov是的,我想顯示某處。 – 2012-01-17 07:22:43

回答

3

你可以通過這個代碼得到:

Formatter format=new Formatter(); 
double d1=Double.parseDouble(format.formatNumber(1.33333, 2)); 
double d2=Double.parseDouble(format.formatNumber(10.487586, 3)); 
double d3=Double.parseDouble(format.formatNumber(10.487586, 5)); 
System.out.println("=================: "+d1+"======"+d2+"==========="+d3); 

我在控制檯輸出:

=================:1.33 = ===== 10.487 =========== 10.48758

這裏'2','3'和'5'表示點(。)後面的小數位數。

1

如果你想手工做這可能會幫助你

public static String roundDouble(String s, int presicion){ 
    int initialPos = s.indexOf('.'); 
    String result = s; 
    String pre; 
    String pos; 

    if (initialPos != -1){ 
     pre = s.substring(0, initialPos); 
     pos = s.substring(initialPos + 1, s.length()); 
     if (presicion < pos.length()){ 
      pos = s.substring(initialPos + 1, initialPos + 1 + presicion); 
      int dec = Integer.parseInt(pos); 
      int next = Integer.parseInt(s.substring(initialPos + 1 + presicion, initialPos + 2 + presicion)); //to round the las digit 
      if (next > 4){ 
       dec = dec + 1; 
       pos = dec + ""; 
       if ((dec+"").length() > presicion){ 
        pre = (Integer.parseInt(pre) + 1) + ""; 
        pos = "0"; 
       } 
      } 
     } else { 
     } 

     result = pre + "." + pos; 
    } 

    return result; 
} 
1

您可以使用此

public static String roundTwoDecimal(String num) { 
    // Turn random double into a clean currency format (ie 2 decimal places) 
    StringBuffer result; 
    double numValue = Double.parseDouble(num); 
    if (Math.abs(numValue) < .01) { 
     result = new StringBuffer("0.00"); 
    } else { 
     if (numValue > 0) 
      numValue = numValue + 0.005; 
     else 
      numValue = numValue - 0.005; 

     result = new StringBuffer(Double.toString(numValue)); 
     final int point = result.toString().indexOf('.'); 
     if (point > 0) { 
      // If has a decimal point, may need to clip off after 2 decimal 
      // places 
      if (point < (result.length() - 2)) { 
       // eg "3.1415" 
       result = new StringBuffer(result.toString().substring(0, 
         point + 3)); 
      } 
     } 
    } 
    return result.toString(); 
}