Float to currency in Java

跟風遠走 提交于 2019-12-12 01:16:20

问题


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?


回答1:


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.




回答2:


      public static void main(String args[])
      {
      float amount =  2192.05f;
      NumberFormat formatter = new DecimalFormat("###,###,###.##");
       System.out.println("The Decimal Value is:"+formatter.format(amount));
      }


来源:https://stackoverflow.com/questions/13283472/float-to-currency-in-java

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!