zoukankan      html  css  js  c++  java
  • 将小数按照四舍五入保留两位输出

           在刷题的时候经常会要求将得到的结果按照四舍五入保留两位结果打印输出,非常推荐一种简易的方式:

        

    System.out.println(String.format("%.2f",12.51234563));  //12.51
       // 这种匹配相当实用,并且能够自动补0,当然保留3位小数也可,只需将2f --> 3f即可,以此类推;
       //String.format()方法中,字符匹配的格式是一种基于 C 的匹配格式,与正则表达式类似;
    

      

     format用法可以参考这篇博文:https://blog.csdn.net/hddyhg/article/details/83885499

    当然还有其他的保留两位小数输出方法:https://www.cnblogs.com/chenrenshui/p/6128444.html,其代码如下:

    import java.math.BigDecimal;
        import java.text.DecimalFormat;
        import java.text.NumberFormat;
        public class format {
            double f = 111231.5585;
            public void m1() {
                BigDecimal bg = new BigDecimal(f);
                double f1 = bg.setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue();
                System.out.println(f1);
            }
            /**
             * DecimalFormat转换最简便
             */
            public void m2() {
                DecimalFormat df = new DecimalFormat("#.00");
                System.out.println(df.format(f));
            }
            /**
             * String.format打印最简便
             */
            public void m3() {
                System.out.println(String.format("%.2f", f));
            }
            public void m4() {
                NumberFormat nf = NumberFormat.getNumberInstance();
                nf.setMaximumFractionDigits(2);
                System.out.println(nf.format(f));
            }
            public static void main(String[] args) {
                format f = new format();
                f.m1();
                f.m2();
                f.m3();
                f.m4();
            }
        }
    

      

  • 相关阅读:
    BZOJ2219数论之神——BSGS+中国剩余定理+原根与指标+欧拉定理+exgcd
    Luogu 3690 Link Cut Tree
    CF1009F Dominant Indices
    CF600E Lomsat gelral
    bzoj 4303 数列
    CF1114F Please, another Queries on Array?
    CF1114B Yet Another Array Partitioning Task
    bzoj 1858 序列操作
    bzoj 4852 炸弹攻击
    bzoj 3564 信号增幅仪
  • 原文地址:https://www.cnblogs.com/zwwang/p/15083509.html
Copyright © 2011-2022 走看看