Parse a number, ignoring thousand-separating commas. - Java java.lang

Java examples for java.lang:double Format

Description

Parse a number, ignoring thousand-separating commas.

Demo Code


//package com.java2s;

public class Main {
    /**//w w w  .j  a v a2s  .co  m
     * Parse a number, ignoring thousand-separating commas. A negative number
     * will cause an exception.
     */
    public static Integer parseNumber(String s) {
        int result = 0;
        String cleanValue = s.trim().replaceAll(",", "");
        try {
            result = Integer.valueOf(cleanValue);
        } catch (Exception ex) {
            throw new RuntimeException("Invalid value: " + s);
        }
        if (result < 0)
            throw new RuntimeException("Negative value not allowed: " + s);

        return result;
    }
}

Related Tutorials