Java reserved decimal places

Source: Internet
Author: User

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

Retain two decimal places

---------------------------------------------------------------

Method 2:

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 indicates two decimal places #. 0000 four decimal places and so on...

Method 3:

Double D = 3.1415926;

String result = string. Format ("%. 2f ");

%. 2f %. indicates any number of digits before the decimal point. 2 indicates that the result of two decimal places is f indicating the floating point type.

Method 4:

Numberformat ddf1 = numberformat. getnumberinstance ();

Void setmaximumfractiondigits (INT digits)

Number of digits displayed by digits

Sets the maximum number of digits displayed after the decimal point for the formatted object. The last digit 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 );

}

}

 

Related Article

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.