将数字转换为带小数的单词(java)

时间:2013-06-19 05:12:37

标签: java

我想将数字转换为单词,经过一些研究后,我可以成功地将数字转换为英语单词。但是,这仅适用于整数。我想将带小数的数字转换为英语单词,例如:

123.45 - >一百二十三,四十五美分

任何解决方案?

参考:http://pastebin.com/BNL1tdPW

2 个答案:

答案 0 :(得分:5)

由于你拥有所有的基本功能,我只需要一个伪代码建议来获得下半部分:

get the cents-only portion as a double. (0.45)
multiply the cents by 100. (45)
use your normal conversion technique to the English words. (Forty Five)

编辑(如何将仅限美分的部分作为双倍?):

    double money = 123.45;

    int dollars = (int) Math.floor(money);
    double cents = money - dollars;
    int centsAsInt = (int) (100 * cents);

    System.out.println("dollars: " + dollars);
    System.out.println("cents: " + cents);
    System.out.println("centsAsInt: " + centsAsInt);

答案 1 :(得分:1)

使用BigDecimal。您可以按如下方式获得小数部分:

final BigDecimal intPart = new BigDecimal(orig.toBigInteger);
final BigDecimal fracPart = orig.minus(intPart);
final int scale = fractPart.scale();
final String fractPartAsString = fracPart.mult(BigDecimal.TEN.pow(scale));
// treat fractPartAsString
相关问题