2015-06-05 89 views
0

嘿傢伙我有問題,使雙數的percentege。使十進制數的百分比

double pom = cumulativeProbability(GetZ(baby)); 

    Log.d("Pom","" + pom); 

    double pom1 = round(cumulativeProbability(GetZ(baby)),2); 
    Log.d("Pom1", "" + pom1); 

    double pom2 = pom1 * 100; 

    Log.d("Pom2: ", "" + pom2); 

下面是日誌:

06-05 02:30:04.574 13208-13208/com.bojan.readfromcsv D/Pom﹕ 0.5821510290598115 
    06-05 02:30:04.584 13208-13208/com.bojan.readfromcsv D/Pom1﹕ 0.58 
    06-05 02:30:04.584 13208-13208/com.bojan.readfromcsv D/Pom2:﹕ 57.99999999999999 

我想這個給定的POM值四捨五入到小數點後兩位,而我得到這輪功能:

public static double round(double value, int places) { 
    if (places < 0) throw new IllegalArgumentException(); 

    BigDecimal bd = new BigDecimal(value); 
    bd = bd.setScale(places, RoundingMode.HALF_UP); 
    return bd.doubleValue(); 
} 

對於最後的結果pom2我想擁有58%.... Tnx

+2

任何原因,你是通過地方寧願圓,而不是僅僅使用Math.round(pom2) ?? –

+0

圍繞你的最後(pom2)雙。 – hungryghost

回答

0

Try:

double pom2 = round(pom1 * 100, 0); 

編輯:

int pom2 = (int) round(pom1 * 100, 0); 
+0

有了這pom2我越來越58.0 ... – Bukic

+0

Yeeeah tnx maaan現在工作很好:))) – Bukic

0

我假設你不必寫自己的功能全面,那麼爲什麼不使用:

pom2 = (int) Math.round(pom1 * 100); 
+0

是的人這也是工作,但pom2需要int像馬丁穆尼奧斯說... TNX:D – Bukic

0

希望這將有助於:

public class t { 
    public static void main(String args[]) { 
     double pom = 0.5821510290598115; 
     System.out.println("pom = "+pom); 
     double pom1 = Math.round(pom*100)/100.0; 
     System.out.println("pom1 = "+pom1); 
     System.out.println("pom2 = "+Math.round(pom1*100)); 
    } 
} 

其中產生:

$ java t 
pom = 0.5821510290598115 
pom1 = 0.58 
pom2 = 58 

如果您想保留pom2一些數字,說2,這樣做:

System.out.println("pom2 = "+Math.round(pom1*100*100)/100.0);