NumberFormat Locale Parse Roundtrip
Format a number with a locale and parse the result back through the same locale, so the roundtrip restores the value and mismatched locales truncate it.
Code
import java.text.NumberFormat;
import java.text.ParseException;
import java.util.Locale;
public class AmountRoundtrip {
public static void main(String[] args) throws ParseException {
double amount = 1234567.891;
// 同一 locale 内往返:format 产出文本,parse 还原数值
NumberFormat de = NumberFormat.getNumberInstance(Locale.GERMANY);
String deText = de.format(amount);
double deBack = de.parse(deText).doubleValue();
System.out.println("de text: " + deText);
System.out.println("de back: " + deBack + " equal: " + (deBack == amount));
// 换 locale 解析别家的文本:分组符语义不同,结果被截断
NumberFormat us = NumberFormat.getNumberInstance(Locale.US);
double usRead = us.parse(deText).doubleValue();
System.out.println("us reads de text as: " + usRead);
// setParseIntegerOnly:解析在小数点停下,尾部文本被忽略
us.setParseIntegerOnly(true);
System.out.println("integer only: " + us.parse("3.99 extra"));
}
}What the code does
The working surface is the class AmountRoundtrip — everything else is wiring.
Watch out for
- The dependency list is empty; the language runtime covers it all.
Applying it
The run emits 3 labeled sections — de text:, de back:, us reads de text as: — one per step.
Statements that matter
NumberFormat de = NumberFormat.getNumberInstance(Locale.GERMANY);
NumberFormat us = NumberFormat.getNumberInstance(Locale.US);
double deBack = de.parse(deText).doubleValue();
Interactive Tools for This Topic
FAQ
- What does NumberFormat Locale Parse Roundtrip print when run?
- No setup needed: run the file and look for labeled lines like `de text:`, `de back:`, `us reads de text as:` in the output.
Report a problem with this exampleOpens a pre-filled issue on GitHub.