1

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.

8
Contributors
7
Replies
15
Views
11 Years
Discussion Span
Last Post by mubin_89
0

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

0

better to use the setMinimumFractionDigits and setMaximumFractionDigits functions on DecimalFormat.

The format strings can be confusing :)

0

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

0

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

Edited by NavinBhutada: n/a

0
double num = 1001.27124;
System.out.printf("%8.2f\n", num);

Edited by tong1: n/a

0

import java.text.*;

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

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

This article has been dead for over six months. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.