How to convert number to words in java

前端 未结 27 2772
遇见更好的自我
遇见更好的自我 2020-11-21 23:53

We currently have a crude mechanism to convert numbers to words (e.g. using a few static arrays) and based on the size of the number translating that into an english text. B

27条回答
  •  礼貌的吻别
    2020-11-22 00:40

    You can use ICU4J, Just need to add POM entry and code is below for any Number, Country and Language.

    POM Entry

         
            com.ibm.icu
            icu4j
            64.2
        
    

    Code is

    public class TranslateNumberToWord {
    
    /**
     * Translate
     * 
     * @param ctryCd
     * @param lang
     * @param reqStr
     * @param fractionUnitName
     * @return
     */
    public static String translate(String ctryCd, String lang, String reqStr, String fractionUnitName) {
        StringBuffer result = new StringBuffer();
    
        Locale locale = new Locale(lang, ctryCd);
        Currency crncy = Currency.getInstance(locale);
    
        String inputArr[] = StringUtils.split(new BigDecimal(reqStr).abs().toPlainString(), ".");
        RuleBasedNumberFormat rule = new RuleBasedNumberFormat(locale, RuleBasedNumberFormat.SPELLOUT);
    
        int i = 0;
        for (String input : inputArr) {
            CurrencyAmount crncyAmt = new CurrencyAmount(new BigDecimal(input), crncy);
            if (i++ == 0) {
                result.append(rule.format(crncyAmt)).append(" " + crncy.getDisplayName() + " and ");
            } else {
                result.append(rule.format(crncyAmt)).append(" " + fractionUnitName + " ");
            }
        }
        return result.toString();
    }
    
    public static void main(String[] args) {
        String ctryCd = "US";
        String lang = "en";
        String input = "95.17";
    
        String result = translate(ctryCd, lang, input, "Cents");
        System.out.println("Input: " + input + " result: " + result);
    }}
    

    Tested with quite a big number and output would be

    Input: 95.17 result: ninety-five US Dollar and seventeen Cents
    Input: 999999999999999999.99 result: nine hundred ninety-nine quadrillion nine hundred ninety-nine trillion nine hundred ninety-nine billion nine hundred ninety-nine million nine hundred ninety-nine thousand nine hundred ninety-nine US Dollar and ninety-nine Cents 
    

提交回复
热议问题