NumberFormat Parse With ParsePosition

parse() silently ignores trailing garbage; the ParsePosition overload returns null on failure and exposes getIndex and getErrorIndex so bad input is rejected.

JavaForm Validation

Code

snippet
import java.text.NumberFormat;
import java.text.ParseException;
import java.text.ParsePosition;
import java.util.Locale;

public class AmountReader {

    public static void main(String[] args) throws ParseException {
        NumberFormat de = NumberFormat.getNumberInstance(Locale.GERMANY);

        // parse 只消费能解析的前缀,尾部垃圾被静默吞掉
        System.out.println("prefix parse: " + de.parse("1.234,5 kg"));

        // ParsePosition 重载:getIndex 告诉你消费到哪
        ParsePosition pos = new ParsePosition(0);
        de.parse("12,34", pos);
        System.out.println("parsed to index: " + pos.getIndex());

        // 失败时返回 null 并用 errorIndex 标出出错位置
        ParsePosition bad = new ParsePosition(0);
        Number failed = de.parse("kg,1", bad);
        System.out.println("failed: " + (failed == null) + " errorIndex: " + bad.getErrorIndex());

        // 尾部有剩余字符时可以显式拒绝,而不是静默接受
        ParsePosition strict = new ParsePosition(0);
        de.parse("12,34kg", strict);
        System.out.println("leftover starts at: " + strict.getIndex() + " of 7");

        // setParseIntegerOnly:解析到小数点就停
        NumberFormat whole = NumberFormat.getNumberInstance(Locale.US);
        whole.setParseIntegerOnly(true);
        System.out.println("integer only: " + whole.parse("42.7x"));
    }
}

Inside the snippet

Count the class AmountReader as the entire surface area of NumberFormat Parse With ParsePosition.

Putting it to use

The demo output is labeled (prefix parse:, parsed to index:, failed:), so every printed line maps back to its originating operation.

Core lines

NumberFormat de = NumberFormat.getNumberInstance(Locale.GERMANY);
NumberFormat whole = NumberFormat.getNumberInstance(Locale.US);
ParsePosition strict = new ParsePosition(0);

Interactive Tools for This Topic

FAQ

What does NumberFormat Parse With ParsePosition print when run?
The script runs standalone; its 5 labeled outputs include `prefix parse:`, `parsed to index:`, `failed:`.