在 Java 中浮动到货币 [英] Float to currency in Java

查看:62
本文介绍了在 Java 中浮动到货币的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果输入一个数字(浮点数),例如 12500,则该数字将转换为货币格式为 12,500.00.格式将为###,###,###.##".如何使用 java 和 没有 任何 apache utils 或类似的库来做到这一点.逗号将在每 3 位数字后重复,小数点将四舍五入并显示为小数点后 2 位数字.如果 .5 应该是 0.50 并且如果是 .569,它应该是 0.57.有没有通过正则表达式之类的方法解决这个问题?

If a number (float) is input such as 12500, the number is converted to money format as 12,500.00. The format will be '###,###,###.##'. How to do this using java and without any apache utils or similar libraries. A comma will repeat after each 3 digits, and the decimal number will be rounded and shown as 2 digits after decimal places. If .5 it should be .50 and if .569 it should be .57. Is there any solution to this problem through regular expression or anything?

推荐答案

我通过在 Google 上的一点点搜索找到了以下代码...可能对您有所帮助...

I found following code by doing little bit of search on Google... Might be helpful for you...

查看此链接,对理解很有帮助.在此链接中,只有他们提供了必要格式的方法...

Check this link, it is quite helpful to understand. At this link only they have given the way to requisite format...

http://docs.oracle.com/javase/tutorial/i18n/format/numberFormat.html

static public void displayCurrency( Locale currentLocale) {

    Double currencyAmount = new Double(9876543.21);
    Currency currentCurrency = Currency.getInstance(currentLocale);
    NumberFormat currencyFormatter = 
        NumberFormat.getCurrencyInstance(currentLocale);

    System.out.println(
        currentLocale.getDisplayName() + ", " +
        currentCurrency.getDisplayName() + ": " +
        currencyFormatter.format(currencyAmount));
}

前几行代码生成的输出如下:

The output generated by the preceding lines of code is as follows:

French (France), Euro: 9 876 543,21 €
German (Germany), Euro: 9.876.543,21 €
English (United States), US Dollar: $9,876,543.21

在这种情况下,您可以选择区域设置,甚至无需知道特定国家/地区使用的格式即可享受.

In this case you can choose the locale and can enjoy without even knowing the format used in the specific country/place.

这篇关于在 Java 中浮动到货币的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆