Home > Java > javaTutorial > body text

Java's multiple methods to make double retain two decimal places. Java retains two decimal places.

高洛峰
Release: 2017-01-18 16:24:34
Original
3003 people have browsed it

The three results of

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);
Copy after login

are:

3.23
0.00 
2.00
Copy after login

java retains two decimal places:

Method 1:

Rounding

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

retains two decimal places Decimal

Method 2:

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

Example:

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

#.00 means two decimal places, #.0000 means four decimal places, and so on...

Method three:

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

%.2f %. Represents any number of digits before the decimal point 2 Represents two decimal places The result after the format is f Represents floating point type

Method four:

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

digits The number of digits displayed
Sets the maximum number of digits displayed after the decimal point for the formatted object, and the last digit displayed is rounded

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); 
} 
}
Copy after login
import java.text.*;
DecimalFormat df=new DecimalFormat(".##");
double d=1252.2563;
String st=df.format(d);
System.out.println(st);
Copy after login

More java enables double to retain two decimal places For related articles on the multi-method java retaining two decimal places, please pay attention to the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template