java数字格式化_Java数字格式

本文探讨了Java的`NumberFormat`类,用于格式化数字的抽象类,包括货币、百分比和整数的示例。通过`getInstance()`、`getCurrencyInstance()`和`getPercentInstance()`等方法,可以方便地创建不同类型的数字格式器。此外,还展示了如何控制定点数字的位数。
摘要由CSDN通过智能技术生成

java数字格式化

当我看到其他人编写不必要的Java代码并且由于缺乏对已经提供所需功能的JDK类的了解而编写了不必要的Java代码时,我会想到很多次。 这样的一个例子是时间相关的常量的使用硬编码值的写入,如60241440 ,和86400TIMEUNIT提供了更好的,标准化的方法。 在这篇文章中,我看一看一个类的示例,该示例提供了开发人员经常在其上实现的功能: NumberFormat

NumberFormat类是java.text包的一部分,该还包括常用的DateFormatSimpleDateFormat类。 NumberFormat是一个抽象类(没有公共构造函数),其后代的实例是通过具有诸如getInstance()getCurrencyInstanceInstance()getPercentInstance()之类的名称的重载静态方法获得的。

货币

下一个代码清单演示了如何调用NumberFormat.getCurrencyInstance(Locale)来获取NumberFormat的实例,该实例以货币友好格式显示数字。

演示NumberFormat的货币支持
/**
 * Demonstrate use of a Currency Instance of NumberFormat.
 */
public void demonstrateCurrency()
{
   writeHeaderToStandardOutput("Currency NumberFormat Examples");
   final NumberFormat currencyFormat = NumberFormat.getCurrencyInstance(Locale.US);
   out.println("15.5      -> " + currencyFormat.format(15.5));
   out.println("15.54     -> " + currencyFormat.format(15.54));
   out.println("15.345    -> " + currencyFormat.format(15.345));  // rounds to two decimal places
   printCurrencyDetails(currencyFormat.getCurrency());
}

/**
 * Print out details of provided instance of Currency.
 *
 * @param currency Instance of Currency from which details
 *    will be written to standard output.
 */
public void printCurrencyDetails(final Currency currency)
{
   out.println("Concurrency: " + currency);
   out.println("\tISO 4217 Currency Code:           " + currency.getCurrencyCode());
   out.println("\tISO 4217 Numeric Code:            " + currency.getNumericCode());
   out.println("\tCurrency Display Name:            " + currency.getDisplayName(Locale.US));
   out.println("\tCurrency Symbol:                  " + currency.getSymbol(Locale.US));
   out.println("\tCurrency Default Fraction Digits: " + currency.getDefaultFractionDigits());
}

执行上述代码后,结果如下所示:

==================================================================================
= Currency NumberFormat Examples
==================================================================================
15.5      -> $15.50
15.54     -> $15.54
15.345    -> $15.35
Concurrency: USD
 ISO 4217 Currency Code:           USD
 ISO 4217 Numeric Code:            840
 Currency Display Name:            US Dollar
 Currency Symbol:                  $
 Currency Default Fraction Digits: 2

上面的代码和相关的输出表明,用于货币的NumberFormat实例(实际上是DecimalFormat )会根据语言环境自动应用适当的位数和适当的货币符号。

百分比

下一个代码清单和相关的输出演示了NumberFormat使用,以百分比友好格式显示数字。

演示NumberFormat的百分比格式
/**
 * Demonstrate use of a Percent Instance of NumberFormat.
 */
public void demonstratePercentage()
{
   writeHeaderToStandardOutput("Percentage NumberFormat Examples");
   final NumberFormat percentageFormat = NumberFormat.getPercentInstance(Locale.US);
   out.println("Instance of: " + percentageFormat.getClass().getCanonicalName());
   out.println("1        -> " + percentageFormat.format(1));
   // will be 0 because truncated to Integer by Integer division
   out.println("75/100   -> " + percentageFormat.format(75/100));
   out.println(".75      -> " + percentageFormat.format(.75));
   out.println("75.0/100 -> " + percentageFormat.format(75.0/100));
   // will be 0 because truncated to Integer by Integer division
   out.println("83/93    -> " + percentageFormat.format((83/93)));
   out.println("93/83    -> " + percentageFormat.format(93/83));
   out.println(".5       -> " + percentageFormat.format(.5));
   out.println(".912     -> " + percentageFormat.format(.912));
   out.println("---- Setting Minimum Fraction Digits to 1:");
   percentageFormat.setMinimumFractionDigits(1);
   out.println("1        -> " + percentageFormat.format(1));
   out.println(".75      -> " + percentageFormat.format(.75));
   out.println("75.0/100 -> " + percentageFormat.format(75.0/100));
   out.println(".912     -> " + percentageFormat.format(.912));
}
==================================================================================
= Percentage NumberFormat Examples
==================================================================================
1        -> 100%
75/100   -> 0%
.75      -> 75%
75.0/100 -> 75%
83/93    -> 0%
93/83    -> 100%
.5       -> 50%
.912     -> 91%
---- Setting Minimum Fraction Digits to 1:
1        -> 100.0%
.75      -> 75.0%
75.0/100 -> 75.0%
.912     -> 91.2%

代码和百分比的输出NumberFormat使用表明,通过默认的实例NumberFormat (实际上是一个DecimalFormat通过返回在这种情况下) NumberFormat.getPercentInstance(区域)的方法没有小数位,乘所提供的数目由100(假定它是(如果提供,则为百分数的十进制等效值 ),并添加一个百分号(%)。

整数

接下来显示的少量代码及其相关输出演示了NumberFormat使用,以整数格式显示数字。

演示NumberFormat的整数格式
/**
 * Demonstrate use of an Integer Instance of NumberFormat.
 */
public void demonstrateInteger()
{
   writeHeaderToStandardOutput("Integer NumberFormat Examples");
   final NumberFormat integerFormat = NumberFormat.getIntegerInstance(Locale.US);
   out.println("7.65   -> " + integerFormat.format(7.65));
   out.println("7.5    -> " + integerFormat.format(7.5));
   out.println("7.49   -> " + integerFormat.format(7.49));
   out.println("-23.23 -> " + integerFormat.format(-23.23));
}
==================================================================================
= Integer NumberFormat Examples
==================================================================================
7.65   -> 8
7.5    -> 8
7.49   -> 7
-23.23 -> -23

如上面的代码和相关输出所示, NumberFormat方法getIntegerInstance(Locale)返回一个实例,该实例将提供的数字表示为整数。

固定位数

下一个代码清单和相关的输出演示了如何使用NumberFormat打印浮点数的定点表示形式。 换句话说,使用NumberFormat可以表示一个数字,该数字在小数点左边(“整数”数字)和小数点右边(“小数”数字)正好具有规定位数。

演示定点数字的NumberFormat
/**
 * Demonstrate generic NumberFormat instance with rounding mode,
 * maximum fraction digits, and minimum integer digits specified.
 */
public void demonstrateNumberFormat()
{
   writeHeaderToStandardOutput("NumberFormat Fixed-Point Examples");
   final NumberFormat numberFormat = NumberFormat.getNumberInstance();
   numberFormat.setRoundingMode(RoundingMode.HALF_UP);
   numberFormat.setMaximumFractionDigits(2);
   numberFormat.setMinimumIntegerDigits(1);
   out.println(numberFormat.format(234.234567));
   out.println(numberFormat.format(1));
   out.println(numberFormat.format(.234567));
   out.println(numberFormat.format(.349));
   out.println(numberFormat.format(.3499));
   out.println(numberFormat.format(0.9999));
}
==================================================================================
= NumberFormat Fixed-Point Examples
==================================================================================
234.23
1
0.23
0.34
0.35
1

上面的代码和相关的输出演示了对最小“整数”位数的精确控制,该位数代表小数点左边(至少一个,因此在适用时显示为零)和最大“分数”小数点右边的数字。 尽管未显示,但也可以指定最大整数位数和最小分数位数。

结论

我曾经用过这篇文章来研究如何使用NumberFormat来以不同的方式(货币,百分比,整数,固定的小数点等)表示数字,并且通常意味着不需要编写或减少代码来对这些数字进行按摩格式。 当我第一次开始写这篇文章时,我设想包括有关NumberFormat的直接后代( DecimalFormatChoiceFormat )的示例和讨论,但是已经确定这篇文章已经足够冗长了。 我可能会在以后的博客文章中介绍NumberFormat这些后代。

翻译自: https://www.javacodegeeks.com/2014/08/java-numeric-formatting.html

java数字格式化

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值