一、场景
在开发工程中,在金额方面都会定义bigdecimal类型,当然有时候也需要将金额转成字符串。我们可能会很自然的写成 金额.toString()方法如:
amount.getInitTotalAmount().toString()//获取初始预算金额的字符串
String amountInfo="到账"+amount+"元";
当然当金额过小时,转成字符串,是没有任何问题的,但当金额数值较大时,转成的字符串时科学计数法格式,这往往不是我们想要的格式。
因此
amount.getInitTotalAmount().toString()//金额为12000000输出的结果为1.2E+7这种的字符串
然后根据这种字符串,无法做一些想要的业务处理
二、解决
1.查看BigDecimal的API后,得知有个toPlainString()方法, 此方法的返回类型为String ,它返回此BigDecimal对象的字符串表示形式,不需要任何指数。
2.BigDecimal保留2位小数转成数字String amountInfo="到账"+amount.setScale(2,BigDecimal.ROUND_HALF_UP)+"元";
/**
* Returns a string representation of this {@code BigDecimal}
* without an exponent field. For values with a positive scale,
* the number of digits to the right of the decimal point is used
* to indicate scale. For values with a zero or negative scale,
* the resulting string is generated as if the value were
* converted to a num