睡前随手写的,应该还有很多没考虑到得情况
package org.lic.test; import java.math.BigDecimal; import java.math.MathContext; /** * Created by lc on 14-5-30. */ public class Main1 { public static void main(String[] args) { System.out.println(parseDecimal("0.0000235689", false).toString()); System.out.println(parseDecimal("-0.00235689", true).toString()); } // may throw NumberFormatException public static BigDecimal parseDecimal(String src, boolean isRounded) { // check src new BigDecimal(src); if (isRounded) { return new BigDecimal(src).round(new MathContext(2)); } else { String tmp = new BigDecimal(src).round(new MathContext(3)).toString(); return new BigDecimal(tmp.substring(0, tmp.length() - 1)); } } }
多谢。