Java数字格式:DecimalFormat
在Java Numeric Formatting一文中 ,我描述并演示了NumberFormat靜態方法提供的一些有用實例,例如NumberFormat.getNumberInstance(Locale) , NumberFormat.getPercentInstance(Locale) , NumberFormat.getCurrencyInstance(Locale)和NumberFormat.getIntegerInstance(Locale) ) 。 事實證明,所有這些抽象NumberFormat實例實際上都是DecimalFormat實例,它擴展了NumberFormat 。
下一個代碼清單和相關的輸出展示了NumberFormat的“ getInstance”方法返回的所有實例實際上都是DecimalFormat實例。 區分同一DecimalFormat類的這些實例的是它們的屬性的設置,例如最小和最大整數數字(小數點左邊的數字)以及小數位數的最小和最大數目(小數點右邊的數字) 。 它們都共享相同的舍入模式和貨幣設置。
NumberFormat.getInstance()提供的實例是DecimalFormat實例
/*** Write characteristics of provided Currency object to* standard output.** @param currency Instance of Currency whose attributes* are to be written to standard output.*/ public void printCurrencyCharacteristics(final Currency currency) {out.print("\tCurrency: " + currency.getCurrencyCode() + "(ISO 4217 Code: " + currency.getNumericCode() + "), ");out.println(currency.getSymbol() + ", (" + currency.getDisplayName() + ")"); }/*** Writes characteristics of provided NumberFormat instance* to standard output under a heading that includes the provided* description.** @param numberFormat Instance of NumberFormat whose key* characteristics are to be written to standard output.* @param description Description to be included in standard* output.*/ public void printNumberFormatCharacteristics(final NumberFormat numberFormat, final String description) {out.println(description + ": " + numberFormat.getClass().getCanonicalName());out.println("\tRounding Mode: " + numberFormat.getRoundingMode());out.println("\tMinimum Fraction Digits: " + numberFormat.getMinimumFractionDigits());out.println("\tMaximum Fraction Digits: " + numberFormat.getMaximumFractionDigits());out.println("\tMinimum Integer Digits: " + numberFormat.getMinimumIntegerDigits());out.println("\tMaximum Integer Digits: " + numberFormat.getMaximumIntegerDigits());printCurrencyCharacteristics(numberFormat.getCurrency());if (numberFormat instanceof DecimalFormat){final DecimalFormat decimalFormat = (DecimalFormat) numberFormat;out.println("\tPattern: " + decimalFormat.toPattern());} }/*** Display key characteristics of the "standard"* NumberFormat/DecimalFormat instances returned by the static* NumberFormat methods getIntegerInstance(), getCurrencyInstance(),* getPercentInstance(), and getNumberInstance().*/ public void demonstrateDecimalFormatInstancesFromStaticNumberFormatMethods() {final NumberFormat integerInstance = NumberFormat.getIntegerInstance();printNumberFormatCharacteristics(integerInstance, "IntegerInstance");final NumberFormat currencyInstance = NumberFormat.getCurrencyInstance();printNumberFormatCharacteristics(currencyInstance, "CurrencyInstance");final NumberFormat percentInstance = NumberFormat.getPercentInstance();printNumberFormatCharacteristics(percentInstance, "PercentInstance");final NumberFormat numberInstance = NumberFormat.getNumberInstance();printNumberFormatCharacteristics(numberInstance, "NumberInstance"); }
盡管我的上一篇和到目前為止的文章已經演示了通過靜態NumberFormat訪問方法獲取DecimalFormat實例,但是DecimalFormat還具有三個重載的構造函數DecimalFormat() , DecimalFormat(String)和DecimalFormat(String,DecimalFormatSymbols) 。 但是請注意, DecimalFormat的Javadoc文檔中有一條警告,指出“通常,請勿直接調用DecimalFormat構造函數,因為NumberFormat工廠方法可能會返回DecimalFormat以外的子類?!?盡管有Javadoc警告,但我接下來的幾個示例仍使用其直接構造函數實例化DecimalFormat實例,因為這樣做不會造成任何危害。
DecimalFormat實例在很大程度上控制十進制數的表示格式。 下面的代碼針對各種不同的自定義模式運行在先前示例中使用的標準數字集。 代碼清單后的屏幕快照顯示了應用這些模式時如何呈現這些數字。
/*** Apply provided pattern to DecimalFormat instance and write* output of application of that DecimalFormat instance to* standard output along with the provided description.** @param pattern Pattern to be applied to DecimalFormat instance.* @param description Description of pattern being applied.*/ private void applyPatternToStandardSample(final String pattern, final String description) {final DecimalFormat decimalFormat = new DecimalFormat(pattern);printHeader(description + " - Applying Pattern '" + pattern + "'");for (final double theDouble : ourStandardSample){out.println(theDouble + ": " + decimalFormat.format(theDouble));} }/*** Demonstrate various String-based patters applied to* instances of DecimalFormat.*/ public void demonstrateDecimalFormatPatternStringConstructor() {final String sixFixedDigitsPattern = "000000";applyPatternToStandardSample(sixFixedDigitsPattern, "Six Fixed Digits");final String sixDigitsPattern = "###000";applyPatternToStandardSample(sixDigitsPattern, "Six Digits Leading Zeros Not Displayed");final String percentagePattern = "";applyPatternToStandardSample(percentagePattern, "Percentage");final String millePattern = "\u203000";applyPatternToStandardSample(millePattern, "Mille");final String currencyPattern = "\u00A4";applyPatternToStandardSample(currencyPattern, "Currency");final String internationalCurrencyPattern = "\u00A4";applyPatternToStandardSample(internationalCurrencyPattern, "Double Currency");final String scientificNotationPattern = "0.###E0";applyPatternToStandardSample(scientificNotationPattern, "Scientific Notation"); }================================================================== = Six Fixed Digits - Applying Pattern '000000' ================================================================== NaN: 0.25: 000000 0.4: 000000 0.567: 000001 1.0: 000001 10.0: 000010 100.0: 000100 1000.0: 001000 10000.0: 010000 100000.0: 100000 1000000.0: 1000000 1.0E7: 10000000 Infinity: ∞ ================================================================== = Six Digits Leading Zeros Not Displayed - Applying Pattern '###000' ================================================================== NaN: 0.25: 000 0.4: 000 0.567: 001 1.0: 001 10.0: 010 100.0: 100 1000.0: 1000 10000.0: 10000 100000.0: 100000 1000000.0: 1000000 1.0E7: 10000000 Infinity: ∞ ================================================================== = Percentage - Applying Pattern '' ================================================================== NaN: 0.25: %25 0.4: %40 0.567: %57 1.0: %100 10.0: %1000 100.0: %10000 1000.0: %100000 10000.0: %1000000 100000.0: %10000000 1000000.0: %100000000 1.0E7: %1000000000 Infinity: %∞ ================================================================== = Mille - Applying Pattern '‰00' ================================================================== NaN: 0.25: ‰250 0.4: ‰400 0.567: ‰567 1.0: ‰1000 10.0: ‰10000 100.0: ‰100000 1000.0: ‰1000000 10000.0: ‰10000000 100000.0: ‰100000000 1000000.0: ‰1000000000 1.0E7: ‰10000000000 Infinity: ‰∞ ================================================================== = Currency - Applying Pattern '¤' ================================================================== NaN: 0.25: $0 0.4: $0 0.567: $1 1.0: $1 10.0: $10 100.0: $100 1000.0: $1000 10000.0: $10000 100000.0: $100000 1000000.0: $1000000 1.0E7: $10000000 Infinity: $∞ ================================================================== = Double Currency - Applying Pattern '¤' ================================================================== NaN: 0.25: $0 0.4: $0 0.567: $1 1.0: $1 10.0: $10 100.0: $100 1000.0: $1000 10000.0: $10000 100000.0: $100000 1000000.0: $1000000 1.0E7: $10000000 Infinity: $∞ ================================================================== = Scientific Notation - Applying Pattern '0.###E0' ================================================================== NaN: 0.25: 2.5E-1 0.4: 4E-1 0.567: 5.67E-1 1.0: 1E0 10.0: 1E1 100.0: 1E2 1000.0: 1E3 10000.0: 1E4 100000.0: 1E5 1000000.0: 1E6 1.0E7: 1E7 Infinity: ∞對于最后兩個應用DecimalFormat示例,我將通過使用NumberFormat.getInstance(Locale)的首選方法來獲取DecimalFormat的實例。 第一個代碼清單演示了應用于同一double的不同語言環境,然后演示了每種語言的輸出格式。
/*** Provides an instance of DecimalFormat based on the provided instance* of Locale.** @param locale Locale to be associated with provided instance of* DecimalFormat.* @return Instance of DecimalFormat associated with provided Locale.* @throws ClassCastException Thrown if the object provided to me* by NumberFormat.getCurrencyInstance(Locale) is NOT an instance* of class {@link java.text.DecimalFormat}.*/ private DecimalFormat getDecimalFormatWithSpecifiedLocale(final Locale locale) {final NumberFormat numberFormat = NumberFormat.getCurrencyInstance(locale);if (!(numberFormat instanceof DecimalFormat)){throw new ClassCastException("NumberFormat.getCurrencyInstance(Locale) returned an object of type "+ numberFormat.getClass().getCanonicalName() + " instead of DecimalFormat.");}return (DecimalFormat) numberFormat; }/*** Demonstrate formatting of double with various Locales.*/ public void demonstrateDifferentLocalesCurrencies() {final double monetaryAmount = 14.99;out.println("Locale-specific currency representations of " + monetaryAmount + ":");out.println("\tLocale.US: "+ getDecimalFormatWithSpecifiedLocale(Locale.US).format(monetaryAmount));out.println("\tLocale.UK: "+ getDecimalFormatWithSpecifiedLocale(Locale.UK).format(monetaryAmount));out.println("\tLocale.ENGLISH: "+ getDecimalFormatWithSpecifiedLocale(Locale.ENGLISH).format(monetaryAmount));out.println("\tLocale.JAPAN: "+ getDecimalFormatWithSpecifiedLocale(Locale.JAPAN).format(monetaryAmount));out.println("\tLocale.GERMANY: "+ getDecimalFormatWithSpecifiedLocale(Locale.GERMANY).format(monetaryAmount));out.println("\tLocale.CANADA: "+ getDecimalFormatWithSpecifiedLocale(Locale.CANADA).format(monetaryAmount));out.println("\tLocale.CANADA_FRENCH: "+ getDecimalFormatWithSpecifiedLocale(Locale.CANADA_FRENCH).format(monetaryAmount));out.println("\tLocale.ITALY: "+ getDecimalFormatWithSpecifiedLocale(Locale.ITALY).format(monetaryAmount)); }Locale-specific currency representations of 14.99:Locale.US: $14.99Locale.UK: £14.99Locale.ENGLISH: ¤14.99Locale.JAPAN: ¥15Locale.GERMANY: 14,99 €Locale.CANADA: $14.99Locale.CANADA_FRENCH: 14,99 $Locale.ITALY: € 14,99到目前為止,我的DecimalFormat示例專注于格式化表示的數字。 最后一個示例是另一個方向,并從字符串表示形式解析值。
/*** Demonstrate parsing.*/ public void demonstrateParsing() {final NumberFormat numberFormat = NumberFormat.getCurrencyInstance(Locale.US);final double value = 23.23;final String currencyRepresentation = numberFormat.format(value);out.println("Currency representation of " + value + " is " + currencyRepresentation);try{final Number parsedValue = numberFormat.parse(currencyRepresentation);out.println("Parsed value of currency representation " + currencyRepresentation + " is " + parsedValue);}catch (ParseException parseException){out.println("Exception parsing " + currencyRepresentation + parseException);} }Currency representation of 23.23 is $23.23 Parsed value of currency representation $23.23 is 23.23所示的最后一個示例實際上不需要訪問具體的DecimalNumber方法,并且能夠僅使用NumberFormat通告的方法。 本示例使用NumberFormat.format(double)格式化貨幣表示形式,然后解析提供的貨幣表示形式以使用NumberFormat.parse(String)返回原始值。
NumberFormat ,尤其是DoubleFormat ,“格式化和解析任何語言環境的數字”。
翻譯自: https://www.javacodegeeks.com/2015/08/java-numeric-formatting-decimalformat.html
總結
以上是生活随笔為你收集整理的Java数字格式:DecimalFormat的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 努比亚 Z50 手机获推 MyOS14
- 下一篇: 众筹是什么意思?