金融类等项目通常对于金额较大的字段,通常要求千分位显示,数字保留两位小数,分装工具类方便以后工作需要:
-----------------------------------------------------------★菜鸟笔记,如有问题还望留下您宝贵的意见★-------------------------------------------------------------------
----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
说明:
1、井号(#)表示一位数字,逗号是用于分组分隔符的占位符,点是小数点的占位符。
2、如果小数点的右面,值有三位,但是式样只有两位。format方法通过四舍五入处理。
3、0 - 如果对应位置上没有数字,则用零代替
4、# - 如果对应位置上没有数字,则保持原样(不用补);如果最前、后为0,则保持为空。
5、正负数模板用分号(;)分割
----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
方法一:
- package com.mo.util;
-
- import java.text.DecimalFormat;
-
-
-
-
-
-
-
-
- public class FmtMicrometer {
-
-
-
-
-
-
-
-
- public static String fmtMicrometer(String text) {
- DecimalFormat df = null;
- if (text.indexOf(".") > 0) {
- if (text.length() - text.indexOf(".") - 1 == 0) {
- df = new DecimalFormat("###,##0.");
- } else if (text.length() - text.indexOf(".") - 1 == 1) {
- df = new DecimalFormat("###,##0.0");
- } else {
- df = new DecimalFormat("###,##0.00");
- }
- } else {
- df = new DecimalFormat("###,##0");
- }
- double number = 0.0;
- try {
- number = Double.parseDouble(text);
- } catch (Exception e) {
- number = 0.0;
- }
- return df.format(number);
- }
-
- }
在实体类中使用方法:Bean类
- package com.mo.test;
-
- import com.mo.util.FmtMicrometer;
-
-
-
-
-
-
-
-
- public class QueryXXDao {
-
- private String money;
-
- public String getMoney() {
- return FmtMicrometer.fmtMicrometer(money);
- }
-
- public void setMoney(String money) {
- this.money = FmtMicrometer.fmtMicrometer(money);
- }
-
- @Override
- public String toString() {
- return "QueryXXDao [money=" + money + ", getMoney()=" + getMoney()
- + ", getClass()=" + getClass() + ", hashCode()=" + hashCode()
- + ", toString()=" + super.toString() + "]";
- }
-
-
- }
使用时,直接调用方法就即可
================================================邪恶分隔符======================================================
方法二:
不推荐此方法,小数的话存在精度问题,也可自行封装方法处理,自己在main方法中测试了下
- public static void main(String[] args) throws ParseException {
-
- NumberFormat numberFormat1 = NumberFormat.getNumberInstance();
- System.out.println(numberFormat1.format(11122.33));
-
- NumberFormat numberFormat2 = NumberFormat.getNumberInstance();
- System.out.println(numberFormat2.format(11122.00));
-
- NumberFormat numberFormat3 = NumberFormat.getNumberInstance();
- numberFormat3.setGroupingUsed(false);
- System.out.println(numberFormat3.format(11122.33));
-
-
- String amount1 = "13,000.00";
- double d1 = new DecimalFormat().parse(amount1).doubleValue();
- System.out.println(String.valueOf(d1));
- }