java格式化数字、货币、金钱


网上摘来的,以后可能会用到

 java开发中经常会有数字、货币金钱等格式化需求,货币保留几位小数,货币前端需要加上货币符号等。可以用java.text.NumberFormat和java.text.DecimalFormat实现。

 1 第一种:比如网上交易系统,数字保留4位小数:
 2  public static void main(String[] args){
 3      NumberFormat nf = new DecimalFormat("##.####");
 4      Double d = 554545.4545454;
 5      String str = nf.format(d);
 6      System.out.println(str);
 7      //输出554545.4545
 8 }
 9 
10 
11 第二种:比如网上交易系统,金钱数字保留4位小数且以“¥”开头:
12  public static void main(String[] args){
13     NumberFormat nf = new DecimalFormat("$##.####");
14     Double d = 554545.4545454;
15     String str = nf.format(d);
16     System.out.println(str);
17     //$554545.4545
18 }
19 
20 
21 第三种:比如网上交易系统,金钱数字保留4位小数且三位三位的隔开:
22  public static void main(String[] args){
23     NumberFormat nf = new DecimalFormat("#,###.####");
24     Double d = 554545.4545454;
25     String str = nf.format(d);
26     System.out.println(str);
27     //554,545.4544;
28  }

 


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM