zoukankan      html  css  js  c++  java
  • java保留小数后两位的四种写法


    import java.math.BigDecimal;
    import java.math.RoundingMode;
    import java.text.DecimalFormat;

    /**
    * Double类型数据处理类
    * @author wjx
    * @date 2017/10/17.
    */
    public class NumberUtil {

    public static Double saveOneBit(Double d){
    DecimalFormat format = new DecimalFormat("#0.###");
    format.setRoundingMode(RoundingMode.FLOOR);
    String result = format.format(d);
    return Double.parseDouble(result);
    }

    /**
    * 保留一位小数,不进行四舍五入
    * @param d
    * @return
    */
    public static Double saveOneBitOne(Double d){
    BigDecimal bd = new BigDecimal(d);
    Double tem = bd.setScale(1,BigDecimal.ROUND_FLOOR).doubleValue();
    return tem;
    }

    /**
    * 保留一位小数,进行四舍五入
    * @param d
    * @return
    */
    public static Double saveOneBitOneRound(Double d){
    BigDecimal bd = new BigDecimal(d);
    Double tem = bd.setScale(1,BigDecimal.ROUND_HALF_UP).doubleValue();
    return tem;
    }

    /**
    * 保留两位小数,不进行四舍五入
    * @param d
    * @return
    */
    public static Double saveOneBitTwo(Double d){
    BigDecimal bd = new BigDecimal(d);
    Double tem = bd.setScale(2,BigDecimal.ROUND_FLOOR).doubleValue();
    return tem;
    }

    /**
    * 保留两位小数,进行四舍五入
    * @param d
    * @return
    */
    public static Double saveOneBitTwoRound(Double d){
    BigDecimal bd = new BigDecimal(d);
    Double tem = bd.setScale(2,BigDecimal.ROUND_HALF_UP).doubleValue();
    return tem;
    }

    /**
    * 保留一位小数,进行四舍五入(该方法经测试 较为精准)
    * @param d
    * @return
    */
    public static Double saveOneBitOneRound(Double d){
    String str = String.format("%.1f",d);
    double c = Double.parseDouble(str);
    return c;
    }


    public static void main(String [] args){
    double a = saveOneBitOneRound(1200.48);
    System.out.println(a);
    double b = Double.parseDouble(String.valueOf(a));
    System.out.println(b);
    }
    }
  • 相关阅读:
    Activex打包于发布完整版---ActiveX打包
    同步和异步的区别
    QoS的构建模块与机制
    GLSL语言内置的变量详解
    jquery中的DOM操作
    varchar和Nvarchar区别
    使用SqlServer中的float类型时发现的问题
    SQL2005,错误 0xc00470fe 数据流任务 产品级别对于 组件“源
    SQL SERVER SQLOS的任务调度
    隐式事务(转)
  • 原文地址:https://www.cnblogs.com/wjxbk/p/8882233.html
Copyright © 2011-2022 走看看