JAVA数字千分位和小数点的现实代码(处理金额问题)

2022-07-29,,,,

金融类等项目通常对于金额较大的字段,通常要求千分位显示,数字保留两位小数,分装工具类方便以后工作需要:

说明:

1、井号(#)表示一位数字,逗号是用于分组分隔符的占位符,点是小数点的占位符。

2、如果小数点的右面,值有三位,但是式样只有两位。format方法通过四舍五入处理。

3、0 - 如果对应位置上没有数字,则用零代替

4、# - 如果对应位置上没有数字,则保持原样(不用补);如果最前、后为0,则保持为空。

5、正负数模板用分号(;)分割

方法一:

package com.mo.util; 
import java.text.decimalformat;
 
/**
 * @classname: fmtmicrometer
 * @description: 格式化数字为千分位工具类
 * @author wsq e-mail:
 * @date 2017-6-1 下午02:25:57
 * 
 */
public class fmtmicrometer {
 
 /**
 * @title: fmtmicrometer
 * @description: 格式化数字为千分位
 * @param text
 * @return  设定文件
 * @return string  返回类型
 */
 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;
 
/**
 * @classname: queryxxdao
 * @description: xx查询bean类
 * @author wsq e-mail:
 * @date 2017-6-1 下午04:15:10
 * 
 */
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)); //结果是11,122.33
 
 numberformat numberformat2 = numberformat.getnumberinstance();
 system.out.println(numberformat2.format(11122.00)); //结果是11,122
 
 numberformat numberformat3 = numberformat.getnumberinstance();
 numberformat3.setgroupingused(false); //设置了以后不会有千分位,如果不设置,默认是有的
 system.out.println(numberformat3.format(11122.33)); //结果是11122.33 
 
 //将一个可能包含千分位的数字转换为不含千分位的形式:
 string amount1 = "13,000.00";
 double d1 = new decimalformat().parse(amount1).doublevalue(); //这里使用的是parse,不是format
 system.out.println(string.valueof(d1)); //结果是13000.0
 }

补充知识:java bigdecimal用法详解(保留小数,四舍五入,数字格式化,科学计数法转数字等)

一、简介

java在java.math包中提供的api类bigdecimal,用来对超过16位有效位的数进行精确的运算。双精度浮点型变量double可以处理16位有效数。在实际应用中,需要对更大或者更小的数进行运算和处理。

float和double只能用来做科学计算或者是工程计算,在商业计算中要用java.math.bigdecimal。

bigdecimal所创建的是对象,我们不能使用传统的+、-、*、/等算术运算符直接对其对象进行数学运算,而必须调用其相对应的方法。

方法中的参数也必须是bigdecimal的对象。构造器是类的特殊方法,专门用来创建对象,特别是带有参数的对象。

二、构造器描述

bigdecimal(int) 创建一个具有参数所指定整数值的对象。

bigdecimal(double) 创建一个具有参数所指定双精度值的对象。

bigdecimal(long) 创建一个具有参数所指定长整数值的对象。

bigdecimal(string) 创建一个具有参数所指定以字符串表示的数值的对象。

三、方法描述

add(bigdecimal) bigdecimal对象中的值相加,然后返回这个对象。

subtract(bigdecimal) bigdecimal对象中的值相减,然后返回这个对象。

multiply(bigdecimal) bigdecimal对象中的值相乘,然后返回这个对象。

divide(bigdecimal) bigdecimal对象中的值相除,然后返回这个对象。

tostring() 将bigdecimal对象的数值转换成字符串。

doublevalue() 将bigdecimal对象中的值以双精度数返回。

floatvalue() 将bigdecimal对象中的值以单精度数返回。

longvalue() 将bigdecimal对象中的值以长整数返回。

intvalue() 将bigdecimal对象中的值以整数返回。

四、常用方法

4.1、保留两位小数

/** 
 * 保留两位小数 
 */ 
@org.junit.test 
public void formattest() { 
  double num=13.154215; 
 
  //方式一 
  decimalformat df1 = new decimalformat("0.00"); 
  string str = df1.format(num); 
  system.out.println(str); //13.15 
 
  //方式二 
  // #.00 表示两位小数 #.0000四位小数 
  decimalformat df2 =new decimalformat("#.00"); 
  string str2 =df2.format(num); 
  system.out.println(str2); //13.15 
 
  //方式三 
  //%.2f %. 表示 小数点前任意位数  2 表示两位小数 格式后的结果为f 表示浮点型 
  string result = string.format("%.2f", num); 
  system.out.println(result); //13.15 
} 

string.formate用法详解:

  @test 
  public void test1() { //4.1541483776749997e9 
    double a = 4887233385.5; 
    double b = 0.85; 
     
    system.out.println("result1-->"+a*b); // result1-->4.1541483776749997e9 
     
    bigdecimal a1 = new bigdecimal(a); 
    bigdecimal b1 = new bigdecimal(b); 
     
    system.out.println("result2-->"+a1.multiply(b1));//result2-->4154148377.674999891481619无限不循环 
     
    bigdecimal abigdecimal = new bigdecimal(string.valueof(a)); 
    bigdecimal bbigdecimal = new bigdecimal(string.valueof(b)); 
     
    // 或者下面这种写法 
//   bigdecimal abigdecimal = new bigdecimal(double.tostring(a)); 
//   bigdecimal bbigdecimal = new bigdecimal(double.tostring(b)); 
   
    system.out.println("result3-->"+abigdecimal.multiply(bbigdecimal)); //result3-->4154148377.675  
  } 

4.2、四舍五入

 

/** 
 * 四舍五入 
 */ 
@test 
public void test2() { 
  double num = 111231.5585; 
  bigdecimal b = new bigdecimal(num); 
  //保留2位小数 
  double result = b.setscale(2, bigdecimal.round_half_up).doublevalue(); 
  system.out.println(result); //111231.56 
} 

bigdecimal.setscale()方法用于格式化小数点

setscale(1)表示保留一位小数,默认用四舍五入方式

setscale(1,bigdecimal.round_down)直接删除多余的小数位,如2.35会变成2.3

setscale(1,bigdecimal.round_up)进位处理,2.35变成2.4

setscale(1,bigdecimal.round_half_up)四舍五入,2.35变成2.4

setscaler(1,bigdecimal.round_half_down)四舍五入,2.35变成2.3,如果是5则向下舍

setscaler(1,bigdecimal.round_ceiling)接近正无穷大的舍入

setscaler(1,bigdecimal.round_floor)接近负无穷大的舍入,数字>0和round_up作用一样,数字<0和round_down作用一样

setscaler(1,bigdecimal.round_half_even)向最接近的数字舍入,如果与两个相邻数字的距离相等,则向相邻的偶数舍入。

注释:

1:scale指的是你小数点后的位数。比如123.456则score就是3.

score()就是bigdecimal类中的方法啊。

比如:bigdecimal b = new bigdecimal("123.456");

b.scale(),返回的就是3.

2:roundingmode是小数的保留模式。它们都是bigdecimal中的常量字段,有很多种。

比如:bigdecimal.round_half_up表示的就是4舍5入。

3:pubilc bigdecimal divide(bigdecimal divisor, int scale, int roundingmode)

的意思是说:我用一个bigdecimal对象除以divisor后的结果,并且要求这个结果保留有scale个小数位,roundingmode表示的就是保留模式是什么,是四舍五入啊还是其它的,你可以自己选!

4:对于一般add、subtract、multiply方法的小数位格式化如下:

bigdecimal mdata = new bigdecimal("9.655").setscale(2, bigdecimal.round_half_up);
    system.out.println("mdata=" + mdata);
----结果:----- mdata=9.66

4.3、格式化

由于numberformat类的format()方法可以使用bigdecimal对象作为其参数,可以利用bigdecimal对超出16位有效数字的货币值,百分值,以及一般数值进行格式化控制。

/** 
 * 格式化 
 */ 
@test 
public void test3() { 
  numberformat currency = numberformat.getcurrencyinstance(); //建立货币格式化引用 
  numberformat percent = numberformat.getpercentinstance(); //建立百分比格式化引用 
  percent.setmaximumfractiondigits(3); //百分比小数点最多3位 
 
  bigdecimal loanamount = new bigdecimal("150.48"); //贷款金额 
  bigdecimal interestrate = new bigdecimal("0.008"); //利率 
  bigdecimal interest = loanamount.multiply(interestrate); //相乘 
 
  system.out.println("贷款金额:\t" + currency.format(loanamount)); //贷款金额: ¥150.48 
  system.out.println("利率:\t" + percent.format(interestrate)); //利率: 0.8% 
  system.out.println("利息:\t" + currency.format(interest)); //利息: ¥1.20 
} 
@test 
public void test3() { 
  decimalformat df = new decimalformat(); 
  double data = 1234.56789; //格式化之前的数字 
 
  //1、定义要显示的数字的格式(这种方式会四舍五入) 
  string style = "0.0"; 
  df.applypattern(style); 
  system.out.println("1-->" + df.format(data)); //1234.6 
 
  //2、在格式后添加诸如单位等字符 
  style = "00000.000 kg"; 
  df.applypattern(style); 
  system.out.println("2-->" + df.format(data)); //01234.568 kg 
 
 
  //3、 模式中的"#"表示如果该位存在字符,则显示字符,如果不存在,则不显示。 
  style = "##000.000 kg"; 
  df.applypattern(style); 
  system.out.println("3-->" + df.format(data)); //1234.568 kg 
 
  //4、 模式中的"-"表示输出为负数,要放在最前面 
  style = "-000.000"; 
  df.applypattern(style); 
  system.out.println("4-->" + df.format(data)); //-1234.568 
 
 
  //5、 模式中的","在数字中添加逗号,方便读数字 
  style = "-0,000.0#"; 
  df.applypattern(style); 
  system.out.println("5-->" + df.format(data)); //5-->-1,234.57 
 
 
  //6、模式中的"e"表示输出为指数,"e"之前的字符串是底数的格式, 
  // "e"之后的是字符串是指数的格式 
  style = "0.00e000"; 
  df.applypattern(style); 
  system.out.println("6-->" + df.format(data)); //6-->1.23e003 
 
 
  //7、 模式中的"%"表示乘以100并显示为百分数,要放在最后。 
  style = "0.00%"; 
  df.applypattern(style); 
  system.out.println("7-->" + df.format(data)); //7-->123456.79% 
 
 
  //8、 模式中的"\u2030"表示乘以1000并显示为千分数,要放在最后。 
  style = "0.00\u2030"; 
  //在构造函数中设置数字格式 
  decimalformat df1 = new decimalformat(style); 
  //df.applypattern(style); 
  system.out.println("8-->" + df1.format(data)); //8-->1234567.89‰ 
} 

4.4、bigdecimal比较

bigdecimal是通过使用compareto(bigdecimal)来比较的,具体比较情况如下:

/** 
 * 注意不能使用equals方法来比较大小。 
 * 
 * 使用bigdecimal的坏处是性能比double和float差,在处理庞大,复杂的运算时尤为明显,因根据实际需求决定使用哪种类型。 
 */ 
@test 
public void test4() { 
  bigdecimal a = new bigdecimal("1"); 
  bigdecimal b = new bigdecimal("2"); 
  bigdecimal c = new bigdecimal("1"); 
  int result1 = a.compareto(b); 
  int result2 = a.compareto(c); 
  int result3 = b.compareto(a); 
 
  system.out.println(result1); //-1 
  system.out.println(result2); //0 
  system.out.println(result3); //1 
} 

4.5、科学计数法

有些项目可能会涉及到从excel导入数据,但如果excel里单元格类型为数值,但内容数据太长时(如银行账号),导入时,会默认读取为科学计数法,用以下代码便轻松解决。

@test 
public void test5() { 
  bigdecimal bd = new bigdecimal("3.40256010353e11"); 
  string result = bd.toplainstring(); 
  system.out.println(result); //340256010353 
} 

4.6、java中价格的数字中间有逗号的处理

@test 
public void test1() { 
  java.util.stringtokenizer st = new stringtokenizer( "123,456,789", ","); 
  stringbuffer sb = new stringbuffer(); 
  while(st.hasmoretokens())  { 
    sb.append(st.nexttoken()); 
  } 
  system.out.println(sb); //123456789 
} 
 
@test 
public void test2() { 
  string str = "123,456,789"; 
  str = str.replace(",", ""); 
  system.out.println(str); //123456789 
} 

4.7.精确计算

double value1=1.00; 
string value2 = "1.00"; 
bigdecimal b1 = new bigdecimal(double.valueof(value1)); 
bigdecimal b1 = new bigdecimal(string.valueof(value2)); 
 
 public bigdecimal add(bigdecimal value);            //加法 
 public bigdecimal subtract(bigdecimal value);          //减法  
 public bigdecimal multiply(bigdecimal value);          //乘法 
 public bigdecimal divide(bigdecimal value);           //除法 

下面是一个工具类,该工具类提供加,减,乘,除运算。

public class arith { 
  /** 
   * 提供精确加法计算的add方法 
   * @param value1 被加数 
   * @param value2 加数 
   * @return 两个参数的和 
   */ 
  public static double add(double value1,double value2){ 
    bigdecimal b1 = new bigdecimal(double.valueof(value1)); 
    bigdecimal b2 = new bigdecimal(double.valueof(value2)); 
    return b1.add(b2).doublevalue(); 
  } 
   
  /** 
   * 提供精确减法运算的sub方法 
   * @param value1 被减数 
   * @param value2 减数 
   * @return 两个参数的差 
   */ 
  public static double sub(double value1,double value2){ 
    bigdecimal b1 = new bigdecimal(double.valueof(value1)); 
    bigdecimal b2 = new bigdecimal(double.valueof(value2)); 
    return b1.subtract(b2).doublevalue(); 
  } 
   
  /** 
   * 提供精确乘法运算的mul方法 
   * @param value1 被乘数 
   * @param value2 乘数 
   * @return 两个参数的积 
   */ 
  public static double mul(double value1,double value2){ 
    bigdecimal b1 = new bigdecimal(double.valueof(value1)); 
    bigdecimal b2 = new bigdecimal(double.valueof(value2)); 
    return b1.multiply(b2).doublevalue(); 
  } 
   
  /** 
   * 提供精确的除法运算方法div 
   * @param value1 被除数 
   * @param value2 除数 
   * @param scale 精确范围 
   * @return 两个参数的商 
   * @throws illegalaccessexception 
   */ 
  public static double div(double value1,double value2,int scale) throws illegalaccessexception{ 
    //如果精确范围小于0,抛出异常信息 
    if(scale<0){      
      throw new illegalaccessexception("精确度不能小于0"); 
    } 
    bigdecimal b1 = new bigdecimal(double.valueof(value1)); 
    bigdecimal b2 = new bigdecimal(double.valueof(value2)); 
    return b1.divide(b2, scale).doublevalue();   
  } 
} 

以上这篇java数字千分位和小数点的现实代码(处理金额问题)就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持。

《JAVA数字千分位和小数点的现实代码(处理金额问题).doc》

下载本文的Word格式文档,以方便收藏与打印。