• 【转】Java保留固定小数位的4种方法


    package com.test;
    
    import java.math.BigDecimal;
    import java.text.DecimalFormat;
    import java.text.NumberFormat;
    public class Main {
        /**
         * 测试用例为保留8位
         * */
        double f = 1234.1234567898789;
        /**
         * 由于 BigDecimal 对象是不可变的,此方法的调用不会 导致初始对象被修改;
         * newScale - 要返回的 BigDecimal 值的标度;
         * roundingMode - 要应用的舍入模式;
         * ROUND_HALF_UP 舍入模式为四舍五入;
         * */
        public void method_01() {
            BigDecimal bg = new BigDecimal(f);
            double f1 = bg.setScale(8, BigDecimal.ROUND_HALF_UP).doubleValue();
            System.out.println(f1);
        }
        /**
         * DecimalFormat转换最简便
         */
        public void method_02() {
            DecimalFormat df = new DecimalFormat("#.00000000");
            System.out.println(df.format(f));
        }
        /**
         * String.format打印最简便
         */
        public void method_03() {
            System.out.println(String.format("%.8f", f));
        }
        public void method_04() {
            NumberFormat nf = NumberFormat.getNumberInstance();
            nf.setMaximumFractionDigits(8);
            System.out.println(nf.format(f));
        }
        public static void main(String[] args) {
            Main test = new Main();
            test.method_01();
            test.method_02();
            test.method_03();
            test.method_04();
        }
    }
    结果:
    1234.12345679 1234.12345679 1234.12345679 1,234.12345679
  • 相关阅读:
    涂鸦
    触发事件续
    触摸事件基本介绍
    背景平铺
    屏幕截图
    图片的裁剪
    图片水印
    UIKit绘图方法
    Java范型学习笔记
    《Head first设计模式》学习笔记
  • 原文地址:https://www.cnblogs.com/Richard-xie/p/3403438.html
Copyright © 2020-2023  润新知