搜索
首页JavaJava基础java如何保留小数点后两位

方法:1、用format方法,语法“String.format("%.2f",数值)”;2、用DecimalFormat的format方法;3、用setScale方法进行四舍五入;4、用setMaximumFractionDigits方法。

java如何保留小数点后两位

本教程操作环境:windows7系统、java10版、DELL G3电脑。

方法一:String的format方法(推荐)

double f = 111231.5585;
System.out.println(String.format("%.2f", f));

方法二:DecimalFormat的format方法

double f = 111231.5585;
DecimalFormat df = new DecimalFormat("#.00");            
System.out.println(df.format(f));

方法三:BigDecimal的setScale方法

double f = 111231.5585;
BigDecimal bg = new BigDecimal(f);            
double f1 = bg.setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue();            
System.out.println(f1);

方法四:NumberFormat的setMaximumFractionDigits方法

double f = 111231.5585;
NumberFormat nf = NumberFormat.getNumberInstance();            
nf.setMaximumFractionDigits(2);            
System.out.println(nf.format(f));

代码:

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();
        }
    }

相关视频教程推荐:Java视频教程

以上是java如何保留小数点后两位的详细内容。更多信息请关注PHP中文网其他相关文章!

声明
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn

热AI工具

Undresser.AI Undress

Undresser.AI Undress

人工智能驱动的应用程序,用于创建逼真的裸体照片

AI Clothes Remover

AI Clothes Remover

用于从照片中去除衣服的在线人工智能工具。

Undress AI Tool

Undress AI Tool

免费脱衣服图片

Clothoff.io

Clothoff.io

AI脱衣机

Video Face Swap

Video Face Swap

使用我们完全免费的人工智能换脸工具轻松在任何视频中换脸!

热门文章

热工具

EditPlus 中文破解版

EditPlus 中文破解版

体积小,语法高亮,不支持代码提示功能

Dreamweaver CS6

Dreamweaver CS6

视觉化网页开发工具

Atom编辑器mac版下载

Atom编辑器mac版下载

最流行的的开源编辑器

SublimeText3汉化版

SublimeText3汉化版

中文版,非常好用

适用于 Eclipse 的 SAP NetWeaver 服务器适配器

适用于 Eclipse 的 SAP NetWeaver 服务器适配器

将Eclipse与SAP NetWeaver应用服务器集成。