简体   繁体   中英

Regarding rounding off a value to certain decimal point

I was going through the class decimal format as I was trying format a decimal number in Java upto 2 decimal places or 3 decimal places.

I come up with this solution as shown below but please also let me know are there any other alternative that java provides us to achieve the same thing..!!

import java.text.DecimalFormat;

public class DecimalFormatExample {   

    public static void main(String args[])  {

        //formatting numbers upto 2 decimal places in Java
        DecimalFormat df = new DecimalFormat("#,###,##0.00");
        System.out.println(df.format(364565.14));
        System.out.println(df.format(364565.1454));

        //formatting numbers upto 3 decimal places in Java
        df = new DecimalFormat("#,###,##0.000");
        System.out.println(df.format(364565.14));
        System.out.println(df.format(364565.1454));
    }

}

Output:
364,565.14
364,565.15
364,565.140
364,565.145

Please advise what are other alternatives that java provide us to achieve the same thing..!!

If you are bothered by re-defining your DecimalFormat , or if you suspect you'll be needing to do redefine many times, you could also do inline formatting with String.format() . Check the syntax for Formatter especially the Numeric sub-title.

Here is an alternative to round off...

double a = 123.564;
double roundOff = Math.round(a * 10.0) / 10.0;
System.out.println(roundOff);
roundOff = Math.round(a * 100.0) / 100.0;
System.out.println(roundOff);

The output is

123.6
123.56

Number of 0 s while multiplying and dividing decides the rounding off.

Here is one method.

float round(float value, int roundUpTo){
     float x=(float) Math.pow(10,roundUpTo);
     value = value*x; // here you will guard your decimal points from loosing
     value = Math.round(value) ; //this returns nearest int value
     return (float) value/p;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM