Parse a money amount, ignoring $'s and thousand-separating commas. - Java java.lang

Java examples for java.lang:double Format

Description

Parse a money amount, ignoring $'s and thousand-separating commas.

Demo Code


//package com.java2s;
import java.math.BigDecimal;

public class Main {
    /**/*from  w  ww.j  a v a2  s. c  om*/
     * Parse a money amount, ignoring $'s and thousand-separating commas.
     */
    public static BigDecimal parseMoney(String s) {
        BigDecimal result = BigDecimal.ZERO;
        String cleanValue = s.trim().replaceAll("\\$", "");
        cleanValue = cleanValue.replaceAll(",", "");
        try {
            result = new BigDecimal(cleanValue);
        } catch (Exception ex) {
            throw new RuntimeException("Invalid value: " + s);
        }
        if (result.compareTo(BigDecimal.ZERO) < 0)
            throw new RuntimeException("Negative value not allowed: " + s);

        return result;
    }
}

Related Tutorials