Java formats decimals into fixed decimal places-including instances

Source: Internet
Author: User

This article takes the retention of two decimal places as an example. If you have other requirements, you can easily change them.


1. Use Java. Text. decimalformat (recommended)

Java. Text. decimalformat df = new java. Text. decimalformat ("#. 00 ");
DF. Format (number );
Eg:

New decimalformat ("#. 00"). Format (3.1415926) // #. 00 indicates two decimal places #. 0000 four decimal places, and so on.


2. Algorithm Implementation

Double result = (INT) (Number * 100)/100.0;


3. Implementation using the bigdecimal Method

Double F = 111231.5585;
Bigdecimal B = new bigdecimal (f );
Double result = B. setscale (2, bigdecimal. round_half_up). doublevalue ();
Retain two decimal places


4. Use the setmaximumfractiondigits method of numberformat to implement

Numberformat format = numberformat. getnumberinstance ();
Format. setmaximumfractiondigits (INT digits) // digits is the number of digits displayed.

Note: The maximum number of digits displayed after the decimal point is set for the formatted object. The last digit is rounded.

Eg:

import java.text.* ;public class Formula2 {
public static void main(String[] args)  {    double number = 23.5455;    NumberFormat format = NumberFormat.getNumberInstance() ;    format.setMaximumFractionDigits(2);    String result = format.format(number) ;    System.out.print(result);
    }}

Result: 23.55




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.