首页 > 编程语言 >Java中double类型四舍五入的方法总结

Java中double类型四舍五入的方法总结

时间:2023-06-02 21:08:20浏览次数:37  
标签:四舍五入 Java String format double System BigDecimal out


代码:

double a = 13.245;

 

//方法一:
 BigDecimal bd= new BigDecimal(a);
 Double b = bd.setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue();
 System.out.println("方法一: "+b);
 //方法二:
 Double myValue = new BigDecimal(a).setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue();
 java.text.NumberFormat nf = java.text.NumberFormat.getInstance();   
 nf.setGroupingUsed(false);  
 System.out.println("方法二: "+myValue);
 //方法三:
 // #.00 表示两位小数 #.0000四位小数  
 DecimalFormat df2 =new DecimalFormat("#.00");  
 String str2 =df2.format(a);

System.out.println("方法三: "+str2); 

//方法四:  

 

//%.2f 中的% 表示 小数点前任意位数   2 表示两位小数 格式后的结果为f 表示浮点型  
    String result = String.format("%.2f", a);  

 

System.out.println("方法四: "+result);  

解析:

    //保留两位时 :0.245  0.295  保留一位时: 0.45 0.95

    当double  a = 13.245时,输出结果为:

                方法一: 13.24
                方法二: 13.24
                方法三: 13.24

                方法四: 13.25   

 

    当double  a = 13.295时,输出结果为:

                方法一: 13.29

                方法二: 13.29

                方法三: 13.29

                方法四: 13.30

      当保留一位小数时,若小数点后两位是 45 或 95 时,前三个方法也会有误差.

      当double  a = 0.295时,输出结果为:

                方法一:  0.29
                方法二:  0.29
                方法三:  .29
                方法四:  0.30

    当小数点前的数只有一个 0 时,可以发现方法三错的离谱.

    综上,显然,使用第四种方法进行四舍五入更加精确.

 

===

public static void main(String[] args) {
         System.out.println("向上取整:" + (int) Math.ceil(96.1));// 97 (去掉小数凑整:不管小数是多少,都进一)
         System.out.println("向下取整" + (int) Math.floor(96.8));// 96 (去掉小数凑整:不论小数是多少,都不进位)
         System.out.println("四舍五入取整:" + Math.round(96.1));// 96 (这个好理解,不解释)
         System.out.println("四舍五入取整:" + Math.round(96.8));// 97
     }

Java中double类型四舍五入的方法总结_java


mport java.text.DecimalFormat;  
DecimalFormat    df   = new DecimalFormat("######0.00");   

double d1 = 3.23456  
double d2 = 0.0;
double d3 = 2.0;
df.format(d1); 
df.format(d2); 
df.format(d3);

3个结果分别为: 

3.23
0.00 
2.00

java保留两位小数问题:

方式一:

四舍五入  

double   f   =   111231.5585;  
BigDecimal   b   =   new   BigDecimal(f);  
double   f1   =   b.setScale(2,   BigDecimal.ROUND_HALF_UP).doubleValue();

 

保留两位小数 

方式二:

java.text.DecimalFormat   df   =new   java.text.DecimalFormat("#.00");  
df.format(你要格式化的数字);

 

例:

new java.text.DecimalFormat("#.00").format(3.1415926)

#.00 表示两位小数 #.0000四位小数 以此类推...

方式三:

double d = 3.1415926;
String result = String .format("%.2f");

 

%.2f %. 表示 小数点前任意位数   2 表示两位小数 格式后的结果为f 表示浮点型

NumberFormat ddf1=NumberFormat.getNumberInstance() ;
void setMaximumFractionDigits(int digits)

digits 显示的数字位数 
为格式化对象设定小数点后的显示的最多位,显示的最后位是舍入的

import java.text.* ; 
import java.math.* ; 
class TT 
{ 
public static void main(String args[]) 
{ double x=23.5455; 
NumberFormat ddf1=NumberFormat.getNumberInstance() ;

ddf1.setMaximumFractionDigits(2); 
String s= ddf1.format(x) ; 
System.out.print(s); 
} 
}

 

import java.text.*;
DecimalFormat df=new DecimalFormat(".##");
double d=1252.2563;
String st=df.format(d);
System.out.println(st);

 

下面是百度

1. 功能

将程序中的double值精确到小数点后两位。可以四舍五入,也可以直接截断。

比如:输入12345.6789,输出可以是12345.68也可以是12345.67。至于是否需要四舍五入,可以通过参数来决定(RoundingMode.UP/RoundingMode.DOWN等参数)。

2. 实现代码

package com.clzhang.sample;

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

public class DoubleTest {
    
    /**
     * 保留两位小数,四舍五入的一个老土的方法
     * @param d
     * @return
     */
    public static double formatDouble1(double d) {
        return (double)Math.round(d*100)/100;
    }

    
    /**
     * The BigDecimal class provides operations for arithmetic, scale manipulation, rounding, comparison, hashing, and format conversion.
     * @param d
     * @return
     */
    public static double formatDouble2(double d) {
        // 旧方法,已经不再推荐使用
//        BigDecimal bg = new BigDecimal(d).setScale(2, BigDecimal.ROUND_HALF_UP);

        
        // 新方法,如果不需要四舍五入,可以使用RoundingMode.DOWN
        BigDecimal bg = new BigDecimal(d).setScale(2, RoundingMode.UP);

        
        return bg.doubleValue();
    }

    /**
     * NumberFormat is the abstract base class for all number formats. 
     * This class provides the interface for formatting and parsing numbers.
     * @param d
     * @return
     */
    public static String formatDouble3(double d) {
        NumberFormat nf = NumberFormat.getNumberInstance();
        

        // 保留两位小数
        nf.setMaximumFractionDigits(2); 

        
        // 如果不需要四舍五入,可以使用RoundingMode.DOWN
        nf.setRoundingMode(RoundingMode.UP);

        
        return nf.format(d);
    }

    
    /**
     * 这个方法挺简单的。
     * DecimalFormat is a concrete subclass of NumberFormat that formats decimal numbers. 
     * @param d
     * @return
     */
    public static String formatDouble4(double d) {
        DecimalFormat df = new DecimalFormat("#.00");

        
        return df.format(d);
    }

    
    /**
     * 如果只是用于程序中的格式化数值然后输出,那么这个方法还是挺方便的。
     * 应该是这样使用:System.out.println(String.format("%.2f", d));
     * @param d
     * @return
     */
    public static String formatDouble5(double d) {
        return String.format("%.2f", d);
    }

    public static void main(String[] args) {
        double d = 12345.67890;
        
        System.out.println(formatDouble1(d));
        System.out.println(formatDouble2(d));
        System.out.println(formatDouble3(d));
        System.out.println(formatDouble4(d));
        System.out.println(formatDouble5(d));
    }

}

3. 输出

12345.68
12345.68
12,345.68
12345.68
12345.68

在法语环境下,除了前两种方法显示正常之外,后边三种方法会将小数点显示成逗号,如果做国际化要注意

===
 
 package airthmatic;
 public class demo10 { public static void main(String[] args) {
  double n[]={9,1.2,5,3.2,1.1};
   orderNum(n); 
  } /**
   * double 和 int 数字排序
   * @param n
   */
  public static void orderNum(double []n){  for(int i=0;i<n.length-1;i++){
    for(int j=0;j<n.length-1-i;j++){
     double temp=0;
     if(n[j]>n[j+1]){
      temp=n[j+1];
      n[j+1]=n[j];
      n[j]=temp;
     }
    }
   }
   /**
    * 这里是过滤掉整数的double类型
    */
   for(int i=0;i<n.length;i++){
    int temp=(int)n[i];
    if(n[i]%temp==0){
     System.out.println(temp);
    }else{
     System.out.println(n[i]);
    }
   }
  }
 }


 

 

标签:四舍五入,Java,String,format,double,System,BigDecimal,out
From: https://blog.51cto.com/chengzheng183/6404819

相关文章

  • Java 计算数学表达式(字符串解析求值工具)
    Java字符串转换成算术表达式计算并输出结果,通过这个工具可以直接对字符串形式的算术表达式进行运算,并且使用非常简单。这个工具中包含两个类Calculator和ArithHelperCalculator代码如下:importjava.util.Collections;importjava.util.Stack;/***算数表达式求值*......
  • java单例模式几种实现方式
    1、饿汉式(线程安全,调用效率高,但是不能延时加载):publicclassImageLoader{privatestaticImageLoaderinstance=newImageLoader;privateImageLoader(){}publicstaticImageLoadergetInstance(){returninstance;}}一上来就把单例对象创建出来了,要用的时候直......
  • Java8 Lambda表达式
    学习资料:https://www.bilibili.com/video/BV1ci4y1g7qD/?spm_id_from=333.337.search-card.all.click&vd_source=46d50b5d646b50dcb2a208d3946b1598......
  • IDEA集成Java性能分析神器JProfiler
    阅读文本大概需要10分钟。《eclipse集成Java性能分析神器JProfiler》讲解了eclipse集成Jprofiler,这篇讲解一下IDEA如何集成JProfiler。1、在JProfiler中配置IDEA选择IDEA2019这里并不同于Eclipse选择Eclipse的安装目录。IDEA选择的是配置目录,啥为配置目录了呢?其实就是在配置JProfi......
  • Java队列Disruptor 的使用
    、什么是Disruptor 从功能上来看,Disruptor是实现了“队列”的功能,而且是一个有界队列。那么它的应用场景自然就是“生产者-消费者”模型的应用场合了。可以拿JDK的BlockingQueue做一个简单对比,以便更好地认识Disruptor是什么。我们知道BlockingQueue是一个FIFO队列,生......
  • 2014.4.19.12.27_switch_8.28_java switch语句使用注意的四大细节_0.01
    javaswitch语句使用注意的四大细节很多朋友在使用javaswitch语句时,可能没有注意到一些细节,本文将详细介绍使用javaswitch语句四大要点,需要的朋友可以参考下。switch语句的格式如下:(它的功能是选出一段代码执行)switch(整数选择因子){case整数值1:语句;break;case整数值......
  • 2015.4.21.09.05_多态_2015.4.21_深入理解java多态性_0.01
    深入理解Java多态性多态性是指允许不同类的对象对同一消息作出响应。多态性包括参数化多态性和包含多态性。多态性语言具有灵活、抽象、行为共享、代码共享的优势,很好的解决了应用程序函数同名问题。多态有两种表现形式:重载和覆盖首先说重载(overload),是发生在同一类中。与什么父类......
  • JAVA Socket编程
    aliases:[]tags:""summary:[基于TCP/IP和UDP协议的JavaSocket网络通信编程]author:[yaenli]notekey:[20230512-143738]Socket网络模型Socket编程是在TCP/IP、UDP协议上的网络编程,在此之前,先了解下常见的网络模型:OSI七层模型与TCP模型:OSI七层模型详解(OSI......
  • 定时器(JavaScript)的使用
    前言通过定时器自动的做一些事情,例如发送网络请求一、定时器定时器:定时器可以设定时间自动的做某件事情。定时器是一种方法,不是对象,定时器属于window对象。二、定时器具体内容周期性定时器:间隔一定的时间,自动的做某件事情setInterval(函数名,间隔时间)一次性定时器:延迟多长时间做......
  • java 封装
    1.面向对象思想为什么使用面向对象使人和计算机的交流更加流畅;提高开发效率生活中/计算机描述对象对比生活中的对象定义:看的见摸得着的都是对象计算机中的对象的定义:1.类2.属性3.方法类图使用类图描述类:用于分析和设计类;直观,容易理解; ......