一、场景
在开发工程中,在金额方面都会定义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 numerically equal value with zero scale and as * if all the trailing zeros of the zero scale value were present * in the result. * * The entire string is prefixed by a minus sign character '-' * ('\u002D') if the unscaled value is less than * zero. No sign character is prefixed if the unscaled value is * zero or positive. * * Note that if the result of this method is passed to the * {@linkplain #BigDecimal(String) string constructor}, only the * numerical value of this {@code BigDecimal} will necessarily be * recovered; the representation of the new {@code BigDecimal} * may have a different scale. In particular, if this * {@code BigDecimal} has a negative scale, the string resulting * from this method will have a scale of zero when processed by * the string constructor. * * (This method behaves analogously to the {@code toString} * method in 1.4 and earlier releases.) * * @return a string representation of this {@code BigDecimal} * without an exponent field. * @since 1.5 * @see #toString() * @see #toEngineeringString() */ public String toPlainString() { if(scale==0) { if(intCompact!=INFLATED) { return Long.toString(intCompact); } else { return intVal.toString(); } } if(this.scale
最近更新
- 深拷贝和浅拷贝的区别(重点)
- 【Vue】走进Vue框架世界
- 【云服务器】项目部署—搭建网站—vue电商后台管理系统
- 【React介绍】 一文带你深入React
- 【React】React组件实例的三大属性之state,props,refs(你学废了吗)
- 【脚手架VueCLI】从零开始,创建一个VUE项目
- 【React】深入理解React组件生命周期----图文详解(含代码)
- 【React】DOM的Diffing算法是什么?以及DOM中key的作用----经典面试题
- 【React】1_使用React脚手架创建项目步骤--------详解(含项目结构说明)
- 【React】2_如何使用react脚手架写一个简单的页面?