Reputation: 817
float per = (num / (float)totbrwdbksint) * 100;
i m getting the value of per as say 29.475342 . i want it to round off upto two decimal places only.like 29.48 .how to achieve this?
Upvotes: 4
Views: 500
Reputation: 34592
You need to be careful here, this answer is not related to java, it relates to all aspects of decimals in many programming languages hence it is generic. The danger lies with rounding numbers, is this, and it has happened in my experience and know that it can be tricky to deal with:
If you are in this kind of arena of development, then my advice is not to adjust by rounding up/down...it may not show up on small sales of the items, but it could show up elsewhere...an accountant would spot it...Best thing to do is to simply, truncate it, e.g. 29.475342 -> 29.47 and leave it at that, why?, the .005 can add up to big profit/loss.
In conjunction to what is discussed here...electronic tills and registers use their own variety of handling this scenario, instead of dealing with XX.XXXXXXXXXX (like computers, which has 27/28 decimal places), it deals with XX.XX.
Its something to keep in mind...
Hope this helps, Best regards, Tom.
Upvotes: 1
Reputation: 68962
If you need to control how rounding is done you should check BigDecimal ist has several rounding modes. http://java.sun.com/j2se/1.5.0/docs/api/java/math/BigDecimal.html
Upvotes: 1
Reputation: 108879
As Jon implies, format for display. The most succinct way to do this is probably using the String
class.
float f = 70.9999999f;
String toTwoDecPlaces = String.format("%.2f", f);
This will result in the string "71.00"
Upvotes: 1
Reputation: 59
you can use the formatted print method System.out.printf to do the formatted printing if that's what you need
Upvotes: 0
Reputation: 1500515
You should do this as part of the formatting - the floating point number itself doesn't have any concept of "two decimal places".
For example, you can use a DecimalFormat
with a pattern of "#0.00":
import java.text.*;
public class Test
{
public static void main(String[] args)
{
float y = 12.34567f;
NumberFormat formatter = new DecimalFormat("#0.00");
System.out.println(formatter.format(y));
}
}
Upvotes: 5