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.
Code
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
JSON to Zod Schema ConverterInfer typed Zod z.object schemas from JSON payloads locally, supporting nested objects, merged array shapes, enums, nullable fields, and JSDoc comments.JSON Schema ValidatorValidate JSON data against a JSON Schema definition and get detailed error reports. Supports type checking, required fields, and common constraint validation.JSONL / NDJSON InspectorValidate NDJSON and JSON Lines line-by-line, pinpoint syntax errors by line number, analyze key frequencies and types, and export a pretty JSON array.Credit Card Brand DetectorIdentify the card network from a number's prefix and length, validate the Luhn checksum, and show a masked form and the issuer identification number.
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:`.
Report a problem with this exampleOpens a pre-filled issue on GitHub.