Multiple methods to keep double two decimal digits Java preserves two decimal places

Source: Internet
Author: User

Import Java.text.DecimalFormat;  
DecimalFormat    DF   = new DecimalFormat ("##### #0.");   

Double D1 = 3.23456  
double d2 = 0.0;
Double d3 = 2.0;
Df.format (d1); 
Df.format (D2); 
3 results were: 

3.23
0.00 
2.00
Java preserves two-bit decimal questions:
mode one:
rounding  

double   f   =   111231.5585;  
BigDecimal   B   =   new   BigDecimal (f);  
Double   f1   =   B.setscale (2,   bigdecimal.round_half_up). Doublevalue ();  
Retain two decimal 
mode two:

java.text.DecimalFormat   df   =new   java.text.DecimalFormat ("#.00");  
Df.format (the number you want to format);
Example:

new Java.text.DecimalFormat ("#.00"). Format (3.1415926)
#.00 represents two-bit decimal #.0000 four-bit decimal, etc. ...
Mode three:

double d = 3.1415926;
string result = string. Format ("%.2f");
%.2f%. Indicates that the result of an arbitrary number of digits before the decimal point   2 represents a two-bit decimal format is a floating-point type
Mode IV:

NumberFormat ddf1=numberformat.getnumberinstance ();
The number of digits displayed by void setmaximumfractiondigits (int digits) digits is the maximum number of 
digits displayed after a decimal point is set for the formatted object, and the last bit shown is the 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); 
} 



Import java.text.*;
DecimalFormat df=new DecimalFormat (". # #");
Double d=1252.2563;
String St=df.format (d);
System.out.println (ST);

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.