954,554 Members — Technology Publication meets Social Media
Username:
Password:
Lost login information?
Have something to say? Contribute New Article Reply to this Article

How can I get float value with 2 decimal point?

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.

perlsu
Newbie Poster
17 posts since Sep 2005
Reputation Points: 10
Solved Threads: 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

NPH
Junior Poster in Training
55 posts since May 2005
Reputation Points: 10
Solved Threads: 1
 

import java.util.*;

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

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

server_crash
Postaholic
2,111 posts since Jun 2004
Reputation Points: 113
Solved Threads: 20
 

better to use the setMinimumFractionDigits and setMaximumFractionDigits functions on DecimalFormat.

The format strings can be confusing :)

jwenting
duckman
Team Colleague
8,392 posts since Nov 2004
Reputation Points: 1,662
Solved Threads: 337
 

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


[HTML]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);
}
}[/HTML]

Srinivas

cheenu78
Light Poster
45 posts since Jun 2005
Reputation Points: 10
Solved Threads: 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);
NavinBhutada
Newbie Poster
1 post since Aug 2010
Reputation Points: 10
Solved Threads: 0
 
double num = 1001.27124;
System.out.printf("%8.2f\n", num);
tong1
Posting Whiz
358 posts since Jul 2010
Reputation Points: 34
Solved Threads: 72
 

import java.text.*;

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

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

mubin_89
Newbie Poster
1 post since Sep 2011
Reputation Points: 10
Solved Threads: 0
 

This article has been dead for over three months

Post: Markdown Syntax: Formatting Help
You