Percent Format With Fraction Digits
The default percent instance rounds to whole percents; setMaximumFractionDigits restores decimals and parse turns 43.21% back into the ratio 0.4321.
Code
import java.text.NumberFormat;
import java.text.ParseException;
import java.util.Locale;
public class PercentFormatter {
public static void main(String[] args) throws ParseException {
NumberFormat percent = NumberFormat.getPercentInstance(Locale.US);
// 默认百分号格式不带小数位:比例先乘 100 再取整
System.out.println("default 0.4321 -> " + percent.format(0.4321));
System.out.println("default 0.4376 -> " + percent.format(0.4376));
// 想保留小数必须显式设置位数
percent.setMinimumFractionDigits(1);
percent.setMaximumFractionDigits(2);
System.out.println("digits 0.4321 -> " + percent.format(0.4321));
// parse 走反向路径:把 43.21% 还原成比例 0.4321
System.out.println("parsed 43.21% -> " + percent.parse("43.21%"));
}
}The mechanics of this demo — Percent Format With Fraction Digits
The working surface is the class PercentFormatter — everything else is wiring.
Caveats
- Everything the file does is standard-library behavior — no external surface.
Putting it to use
The file’s steps show up in the output as default 0.4321 ->, default 0.4376 ->, digits 0.4321 ->.
Core lines
NumberFormat percent = NumberFormat.getPercentInstance(Locale.US);
percent.setMinimumFractionDigits(1);
percent.setMaximumFractionDigits(2);
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 Formatter & ValidatorFormat, beautify, and validate JSON data with configurable indentation. Instantly catches syntax errors and displays a pretty-printed tree structure.XML FormatterRe-indent minified or messy XML into a readable structure, validating that every opening tag has a matching closing tag.JSON Schema ValidatorValidate JSON data against a JSON Schema definition and get detailed error reports. Supports type checking, required fields, and common constraint validation.
FAQ
- What does Percent Format With Fraction Digits print when run?
- Invoke the file as-is — the `default 0.4321 ->`, `default 0.4376 ->`, `digits 0.4321 ->` prefixes identify which step printed each line.
Report a problem with this exampleOpens a pre-filled issue on GitHub.