ABOUT ME

-

Today
-
Yesterday
-
Total
-
  • BigDecimal Parse
    카테고리 없음 2025. 10. 30. 11:15

     

    private static final Pattern NUMERIC_PATTERN =
        Pattern.compile("^[+-]?(\\d+\\.?\\d*|\\.\\d+)([eE][+-]?\\d+)?$");
    
    public static boolean isNumericFast(String input) {
        if (input == null) return false;
        String s = input.trim();
        if (s.isEmpty()) return false;
        return NUMERIC_PATTERN.matcher(s).matches();
    }

    ✅ 추천 방식: 직접 파싱 + BigDecimal 생성

    문자열을 직접 split('.')으로 나누고,
    정수부와 소수부를 합쳐서 scale을 직접 지정하면
    불필요한 정규화 / trailing zero 처리 없이 5~10배 이상 빨라집니다.

     
    public static BigDecimal fastDecimal(String value) { if (value == null || value.isEmpty()) return BigDecimal.ZERO; value = value.trim(); boolean negative = value.charAt(0) == '-'; if (negative) value = value.substring(1); int dotIndex = value.indexOf('.'); if (dotIndex < 0) { // 정수 BigDecimal bd = new BigDecimal(new BigInteger(value)); return negative ? bd.negate() : bd; } String intPart = value.substring(0, dotIndex); String fracPart = value.substring(dotIndex + 1); // 불필요한 소수부 0은 제거 int end = fracPart.length(); while (end > 0 && fracPart.charAt(end - 1) == '0') end--; if (end != fracPart.length()) fracPart = fracPart.substring(0, end); if (fracPart.isEmpty()) return new BigDecimal(new BigInteger(negative ? "-" + intPart : intPart)); String combined = intPart + fracPart; BigDecimal bd = new BigDecimal(new BigInteger(negative ? "-" + combined : combined), fracPart.length()); return bd; }
     
     

    ⚙️ 실전 팁

    1️⃣ 엑셀 셀 타입 구분

     
    if (cell.getCellType() == CellType.NUMERIC) { BigDecimal bd = BigDecimal.valueOf(cell.getNumericCellValue()) .setScale(6, RoundingMode.HALF_UP); } else { BigDecimal bd = fastDecimal(cell.getStringCellValue()); }

    → 숫자 셀은 빠르게, 문자열 셀은 정밀하게.

    2️⃣ 스케일 통일

    모든 금액 데이터를 나중에 합산·비교하려면 scale 맞춰야 해요.

     
    bd = bd.setScale(6, RoundingMode.HALF_UP);

    3️⃣ 병렬 처리

    엑셀 10만~100만 셀 단위라면 다음 식으로:

     
    cells.parallelStream() .map(MyExcelParser::fastDecimal) .collect(Collectors.toList());

    댓글

Designed by Tistory.