DecimalFormat Pattern Grouping Rounding
Format numbers with explicit DecimalFormat patterns: grouping commas, fixed decimals, percent scaling, sign prefixes, and a declared rounding mode.
Code
import java.math.RoundingMode;
import java.text.DecimalFormat;
import java.text.DecimalFormatSymbols;
import java.util.Locale;
public class ReportNumbers {
public static void main(String[] args) {
// 显式给符号集:grouping 分隔符不随机器默认 Locale 漂移
DecimalFormatSymbols us = DecimalFormatSymbols.getInstance(Locale.US);
DecimalFormat money = new DecimalFormat("#,##0.00", us);
System.out.println("money: " + money.format(1234567.891));
// 模式里去掉逗号就不分组;# 表示可省略位
DecimalFormat plain = new DecimalFormat("0.##", us);
System.out.println("plain: " + plain.format(1234567.891));
// 模式含 % 时数值会自动乘 100 再显示
DecimalFormat pct = new DecimalFormat("0.0%", us);
System.out.println("pct: " + pct.format(0.1834));
// 分号分正负两个子模式,正数带显式 + 号
DecimalFormat delta = new DecimalFormat("+0.0;-0.0", us);
System.out.println("delta: " + delta.format(0.26) + " / " + delta.format(-0.26));
// 默认 HALF_EVEN(银行家舍入):2.125 收到 2.12
System.out.println("default: " + money.format(2.125));
// setRoundingMode(HALF_UP):同一数值变为 2.13,对齐四舍五入习惯
money.setRoundingMode(RoundingMode.HALF_UP);
System.out.println("half-up: " + money.format(2.125));
}
}Inside the snippet
Count the class ReportNumbers and the function main as the entire surface area of DecimalFormat Pattern Grouping Rounding.
Putting it to use
Running the file prints labeled results such as money:, plain:, pct: — each operation’s effect is visible in the output.
Core lines
DecimalFormatSymbols us = DecimalFormatSymbols.getInstance(Locale.US);
DecimalFormat delta = new DecimalFormat("+0.0;-0.0", us);
DecimalFormat money = new DecimalFormat("#,##0.00", us);
Interactive Tools for This Topic
Duration HumanizerTurn a number of seconds into a readable duration such as 1 day, 2 hours, 3 minutes, and show the equivalent in minutes and hours.Git Conventional Commit BuilderBuild and validate Conventional Commits v1.0.0 messages with type, scope, breaking markers, 72-char subject counter, body, footers, and git CLI command.Glob Pattern TesterCompile glob patterns with *, **, ?, character classes, and braces into regex and test them against a list of candidate file paths.Indentation ConverterConvert leading indentation between tabs and spaces at a chosen width, leaving inner content untouched.
FAQ
- What does DecimalFormat Pattern Grouping Rounding print when run?
- Running the file directly is enough — expect labeled output lines such as `money:`, `plain:`, `pct:`.
Report a problem with this exampleOpens a pre-filled issue on GitHub.