Can anyone help me to get the estimate value of float value 1001.27124 to 1001.27? Math.round(float) function return the int value. But I want to get float value result with 2 decimal point; Thanks in advance.

Try this code

double num = 1001.27124;
    	
double newNum = Math.round(num*100.0)/100.0;
System.out.println (newNum);  //prints 1001.27

It works because *100 shifts the numbers to the left twice. Then the round is applied. Then we divide by 100 to shift twice right.

For more help, www.NeedProgrammingHelp.com

import java.util.*;

DecimalFormat dec = new DecimalFormat("###.##");

System.out.println(dec.format(value));

better to use the setMinimumFractionDigits and setMaximumFractionDigits functions on DecimalFormat.

The format strings can be confusing :)

hi,
i believe you can try this program...

import java.math.*;
class TestBigDecimal
{
	public static void main(String args[])
	{
		BigDecimal bd=new BigDecimal(args[0]);
		bd=bd.setScale(2,BigDecimal.ROUND_HALF_EVEN);
		System.out.println(bd);
	}
}

Srinivas

Just in case if someone need to format a double number to some specific fraction length.

There is a class in java.text package called NumberFormat. You can use .setMaximumFractionDigits(fraction) method to set the maximum fraction for double. Then use format(doublevalue) method which returns string with the defined fraction length value. There are more methods which can be useful for NumberFormatting.

NumberFormat nf = NumberFormat.getInstance();
            nf.setMaximumFractionDigits(2);            
            nf.setGroupingUsed(false); 
            // Setting this to true will give you xx,xxx,xxx type of formatting.
            String formattedvalue = nf.format(adoublevalue);
double num = 1001.27124;
System.out.printf("%8.2f\n", num);

import java.text.*;

DecimalFormat dec = new DecimalFormat("###.##");

System.out.println(dec.format(value));

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.