Administrator
发布于 2023-11-17 / 39 阅读
0
0

Java API 高级使用

DecimalFormat

refer to : https://docs.oracle.com/en/java/javase/11/docs/api/java.base/java/text/DecimalFormat.html

public class DecimalFormat extends NumberFormat

DecimalFormat is a concrete subclass of NumberFormat that formats decimal numbers. It has a variety of features designed to make it possible to parse and format numbers in any locale, including support for Western, Arabic, and Indic digits.

It also supports different kinds of numbers, including integers (123), fixed-point numbers (123.4), scientific notation (1.23E4), percentages (12%), and currency amounts ($123). All of these can be localized.

A DecimalFormat comprises a pattern and a set of symbols.

The pattern may be set directly using applyPattern(), or indirectly using the API methods.

The symbols are stored in a DecimalFormatSymbols object. When using the NumberFormat factory methods, the pattern and symbols are read from localized ResourceBundles.

使用

我们经常要将数字进行格式化,比如取2位小数,这是最常见的

DecimalFormat 类主要靠 # 和 0 两种占位符号来指定数字长度。

  • 0 表示,如果位数不足则以 0 填充,
  • #表示,该位数数字存在,就写;该位数不存在,就不写

场景1:保留最多两位小数,舍弃末尾的0.

public static void main(String[] args) {
        DecimalFormat format = new DecimalFormat("0.##");
        //未保留小数的舍弃规则,RoundingMode.FLOOR表示直接舍弃。
        format.setRoundingMode(RoundingMode.FLOOR);
        System.out.println(format.format(11112.345)); // 11112.34
        System.out.println(format.format(11112.3)); // 11112.3
        System.out.println(format.format(11112)); // 11112
        System.out.println(format.format(111120)); // 111120
        System.out.println(format.format(-11112.3)); // -11112.3
    }

评论