JS 中
1. double运算
c = parseFloat(a) + parseFloat(b))
2. 四舍五入,保留两位小数
c = c.toFixed(2);
3. 去掉小数点后面多余的0
c = c.toFixed(2)*100/100;
JAVA中
1. double运算
c = parseFloat(a) + parseFloat(b))
2. 四舍五入,保留两位小数
c = c.toFixed(2);
3. 去掉小数点后面多余的0
c = c.toFixed(2)*100/100;
JAVA中
- //四舍五入,保留指定小数位
- public static Double roundDouble(Object obj, int scale){
- double d = 0;
- try{
- d = Double.parseDouble(obj.toString().replaceAll(",", ""));
- } catch (Exception e) {
- d = 0;
- }
- //四舍五入,保留两位小数
- BigDecimal bd = new BigDecimal(d);
- bd = bd.setScale(scale, BigDecimal.ROUND_HALF_UP);
- d = bd.doubleValue();
- return d;
- }
- //转成字符串,去掉科学计数法
- public static String roundFormat(Object obj){
- String str = "0";
- try{
- Double d = Double.parseDouble(obj.toString().replaceAll(",", ""));
- //四舍五入,保留两位小数
- BigDecimal bd = new BigDecimal(d);
- bd = bd.setScale(2, BigDecimal.ROUND_HALF_UP);
- d = bd.doubleValue();
- //去除科学计数法
- DecimalFormat df = new DecimalFormat("#.##");
- str = df.format(d);
- } catch (Exception e) {
- str = "0";
- }
- return str;
- }
- //除法
- public static Double divideRound(Double a, Double b){
- try {
- if (b == 0) {
- return 0.0;
- } else {
- BigDecimal bd = new BigDecimal(a/b);
- bd = bd.setScale(2, BigDecimal.ROUND_HALF_UP);
- double d = bd.doubleValue();
- bd = null;
- return d;
- }
- } catch (Exception e) {
- return 0.0;
- }
- }
//四舍五入,保留指定小数位
public static Double roundDouble(Object obj, int scale){double d = 0;try{d = Double.parseDouble(obj.toString().replaceAll(",", ""));} catch (Exception e) {d = 0;}//四舍五入,保留两位小数BigDecimal bd = new BigDecimal(d); bd = bd.setScale(scale, BigDecimal.ROUND_HALF_UP);d = bd.doubleValue(); return d;}//转成字符串,去掉科学计数法
public static String roundFormat(Object obj){String str = "0";try{Double d = Double.parseDouble(obj.toString().replaceAll(",", ""));//四舍五入,保留两位小数BigDecimal bd = new BigDecimal(d); bd = bd.setScale(2, BigDecimal.ROUND_HALF_UP);d = bd.doubleValue(); //去除科学计数法 DecimalFormat df = new DecimalFormat("#.##"); str = df.format(d); } catch (Exception e) {str = "0";}return str;}//除法
public static Double divideRound(Double a, Double b){try {if (b == 0) {return 0.0;} else {BigDecimal bd = new BigDecimal(a/b); bd = bd.setScale(2, BigDecimal.ROUND_HALF_UP); double d = bd.doubleValue(); bd = null; return d; }} catch (Exception e) {return 0.0;}}