JAVA----常用小数位处理

常用小数位处理

public class NumUtils {

    /**
     * 获取二位小数
     * 场景:整形数据存储单价( * 100)后, 再除 100,取数据显示
     * @param num
     * @return
     */
    public static double getTwoDecimal(Integer num) {
        return Math.round(num) / 100.00;
    }


    public static Integer getTwoDecimal(String num) {
        return new Double(Math.round(Double.valueOf(StringUtils.trim(num))  * 100)).intValue();
    }

    public static Integer getTwoDecimal(Double num) {
        return new Double(Math.round(num  * 100)).intValue();
    }

    /**
     * 百分比
     * @param num
     * @return
     */
    public static double getPercent(Integer num) {
        if (num <= 0) {
            return 0;
        }

        return num / 100.00;
    }


    /**
     * 计算两个数的百分比,转整形,精确到万位
     * @param num1
     * @param num2 除数
     * @return
     */
    public static Integer getFourDecimal(Double num1, Double num2) {
        return getFourDecimal(num1 / num2);
    }
    // 同等
    public static Integer getFourDecimal(Integer num1, Integer num2) {
        NumberFormat numberFormat = NumberFormat.getInstance();
        numberFormat.setMaximumFractionDigits(2);
        return getFourDecimal(new Double(numberFormat.format(((float) num1 / (float) num2) * 100)) / 100);
    }


    /**
     * 转整形,精确到万位
     * @param num
     * @return
     */
    public static Integer getFourDecimal(Double num) {
        return new Double(Math.round(Double.valueOf(num)  * 10000)).intValue();
    }
    public static Integer getFourDecimal(String num) {
        return new Double(Math.round(Double.valueOf(StringUtils.trim(num))  * 10000)).intValue();
    }


    /**
     * 保留后两位,能四舍五入
     * @param num
     * @return
     */
    public static String fixedTwo(double num) {
        return String.format("%.2f", num);
    }


    /**
     * 亿位, 四舍五入保留2位小数, 展示千分位
     */
    public static String getTwoDecimal(int num) {
        DecimalFormat df = new DecimalFormat("##,##0.00");
        return df.format(num);
    }

    /**
     * 十亿位, 四舍五入保留2位小数,展示千分位
     */
    public static String twoBigDecimal(int num) {
        DecimalFormat df = new DecimalFormat("##,##0.00");
        return df.format(new BigDecimal(num));
    }



    /**
     * 亿位, 四舍五入保留2位小数, 不展示千分位
     */
    public static String twoDecimalNotThousand(Object num) {
        DecimalFormat df = new DecimalFormat("#.00");
        return df.format(num);
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值