2014-04-15 3 views
0

내가 BigDecimal를 배우고 그리고 난 그것이 내가 입력 한 정확한 숫자를 검색 할 rouding되어 라운딩와 나는 그나마 왜자바의 BigDecimal은 다음 코드 번호를

public static BigDecimal parseFromNumberString(String numberString) { 

    if (numberString != null) { 

     String nonSpacedString = 
      numberString.replaceAll("[ \\t\\n\\x0B\\f\\r]", "").replaceAll("%", ""); 

     int indexOfComma = nonSpacedString.indexOf(','); 
     int indexOfDot = nonSpacedString.indexOf('.'); 
     NumberFormat format = null; 

     if (indexOfComma < indexOfDot) { 
      nonSpacedString = nonSpacedString.replaceAll("[,]", ""); 
      format = new DecimalFormat("##.#"); 
     } else if (indexOfComma > indexOfDot) { 
      nonSpacedString = nonSpacedString.replaceAll("[.]", "");  
      DecimalFormatSymbols otherSymbols = new DecimalFormatSymbols(); 
      otherSymbols.setDecimalSeparator(','); 
      format = new DecimalFormat("##,#", otherSymbols); 
     } else { 
      format = new DecimalFormat(); 
     } 
     try { 
      return new BigDecimal(format.parse(nonSpacedString).doubleValue(), new MathContext(12)); 
     } catch (ParseException e) { 
      // unrecognized number format 
      return null; 
     } 
    } 
    return null; 
} 

내가 할 경우 뭔가

public static void main(String[] args){ 
    BigDecimal d = Test.parseFromNumberString("0.39"); 
    System.out.println(d); 
} 
같은

인쇄 된 값은 0,00입니다. 039

+0

나는'0.39000000'을 얻습니다 ... – Nivas

+0

방금 ​​코드를 실행했습니다. '0.390000000000'을 (를) 저장하는 것을 잊었을 수 있습니까? – Dima

답변

0

방금 ​​코드를 실행했는데 얻을 수 있습니다. 0.390000000000 아마도 저장하는 것을 잊었습니까?

프로젝트를 지우고 ide를 다시 시작한 다음 다시 컴파일하십시오. 코드는

+0

내가 0,39를 실행하는 경우에만 얻을 수 있습니다. 0.39를 실행하면 숫자가 반올림됩니다. –

1

이 코드 시도 잘 작동합니다 :

public static BigDecimal parseFromNumberString(String numberString) { 

    if (numberString != null) { 

     String nonSpacedString = 
      numberString.replaceAll("[ \\t\\n\\x0B\\f\\r]", "").replaceAll("%", ""); 

     int indexOfComma = nonSpacedString.indexOf(','); 
     int indexOfDot = nonSpacedString.indexOf('.'); 
     DecimalFormat decimalFormat = new DecimalFormat(); 
     DecimalFormatSymbols symbols = new DecimalFormatSymbols(); 
     String pattern = "#0.0#";   

     if (indexOfComma < indexOfDot) { 
      symbols.setDecimalSeparator('.'); 
     } else if (indexOfComma > indexOfDot) { 
      symbols.setDecimalSeparator(','); 
     } 

     try { 
      decimalFormat = new DecimalFormat(pattern, symbols); 
      decimalFormat.setParseBigDecimal(true); 
      BigDecimal toRet = (BigDecimal) decimalFormat.parse(nonSpacedString); 
      return toRet.setScale(12); 
     } catch (ParseException e) { 
      return null; 
     } 
    } 
    return null; 
} 

public static void main(String... args) { 
    BigDecimal d = Test.parseFromNumberString("0,39"); 
    System.out.println(d); 
} 

당신이 원하는 것을인가를?