读书人

bigdecimal跟string按格式互转

发布时间: 2012-07-27 11:03:00 作者: rapoo

bigdecimal和string按格式互转

代码一:仅保留2位

/** * 数值保留两位小数 *  * @param convert *            转换前数值 * @return 转换后字符串 */public static String changeNumberType(Double convert) {if (convert == null) {return "";}BigDecimal big = new BigDecimal(convert);big.setScale(2, RoundingMode.HALF_UP);DecimalFormat format = new DecimalFormat("##0.00");return format.format(big);}

?

?

代码2:想保留几位就保留几位

/** * 数值保留N小数 *  * @param convert *            转换前数值 * @param scale *            保留小数的位数 * @return 转换后字符串 */public static String changeNumberType(double convert, int scale) {BigDecimal big = new BigDecimal(convert);big.setScale(scale, RoundingMode.HALF_UP);String strFormatRest = "";for (int i = 0; i < scale; i++) {strFormatRest = strFormatRest + "0";}DecimalFormat format = null;if (strFormatRest.length() > 0) {format = new DecimalFormat("##0." + strFormatRest);} else {format = new DecimalFormat("##0");}return format.format(big);}
?

读书人网 >开源软件

热点推荐