How to round up a decimal number to a whole number.
3.50 => 4
4.5 => 5
3.4 => 3
How do you do this in Java? Thanks!
With the standard rounding function? Math.round()
There's also Math.floor() and Math.ceil(), depending on what you need.
You can use
int i = Math.round(f);
long l = Math.round(d);
where f and d are of type float and double, respectively.
And if you're working with only positive numbers, you can also use int i = (int)(d + 0.5).
EDIT: if you want to round negative numbers up (towards positive infinity, such that -5.4 becomes -5, for example), you can use this as well. If you want to round to the higher magnitude (rounding -5.4 to -6), you would be well advised to use some other function put forth by another answer.
Java provides a few functions in the Math class to do this. For your case, try Math.ceil(4.5) which will return 5.
new BigDecimal(3.4);
Integer result = BigDecimal.ROUND_HALF_UP;
Or
Int i = (int)(202.22d);
Using Math.max you can do it like this:
(int) Math.max(1, (long) Math.ceil((double) (34) / 25)
This would give you 2
Related
How do I round a double away from zero in Java?
The operations I know don't do what I want:
Casting it to (int) rounds it toward zero. (int) 3.7 will be 3,
(int) - 3.9 will be -3.
Math.floor() rounds toward minus infinity. Math.floor(3.7) will be 3.0, Math.floor(-3.9) will be -4.0.
Math.ceil() rounds toward plus infinity. Math.ceil(3.7) will be 4.0, Math.ceil(-3.9) will be -3.0.
Math.round() rounds toward the nearest integer.
However I don't have something that rounds away from zero, such that 3.7 becomes 4.0, and -3.9 becomes -4.0.
Is there such a function in Java?
Check the sign of the number:
double roundedAway = (num >= 0) ? Math.ceil(num) : Math.floor(num)
You can either implement your own function, based on your number being positive or negative, or you can use a RoundingMode. It can round explicitly away from zero with UP
It might look something like this
DecimalFormat df = new DecimalFormat("#.#");
df.setRoundingMode(RoundingMode.UP);
System.out.println(df.format(number_here));
It can be done with RoundingMode and BigDecimal:
double roundAway(double value) {
return new BigDecimal(value).setScale(0, RoundingMode.UP).doubleValue();
}
Note: this will convert the double to a BigDecimal with the precise value of the double. To avoid this, you could use BigDecimal.valueOf(double) instead of the constructor which would use the canonical string representation of the double, but since you're about to round it to a whole number, this would involve an unnecessary conversion to a string. See the constructor documentation for more details.
In java
How to roundoff a value(either float, bigdecimal or double) having the following pattern,
(1) If the value is 1.0, i.e., if the decimal is started with zero then this should not rounded off and the value should be the whole number. ie., in this case "1".
(2) If the value is 1.1 i.e., if the decimal place started with number greater than 0, then the whole number should be rounded to the next number. i.e., if 1.1 then it should be 2.
So you want to round anything below 0.1 down to 0 and 0.1 or more to 1.0
long round = Math.round(x + 0.4);
Try this for a start (for float and double)
int rounded = Math.round(x + 0.4);
See https://docs.oracle.com/javase/8/docs/api/java/math/RoundingMode.html. I believe RoundingMode.CEILING is what you want. BigDecimal lets you control the rounding:
new BigDecimal(1.0).setScale(0, RoundingMode.CEILING).doubleValue(); => 1.0
new BigDecimal(1.1).setScale(0, RoundingMode.CEILING).doubleValue(); => 2.0
Guava includes some utility classes for rounding floats and doubles directly with RoundingModes.
DoubleMath.roundToInt(1.0, RoundingMode.CEILING); => 1
DoubleMath.roundToInt(1.1, RoundingMode.CEILING); => 2
Edit: Whoops. I missed the part where rounding 1.01 should result in 1. The other suggested methods are more correct.
Your specification is not entirely clear to me. I understand your question to mean the "ceil" function, that is, 1.01 has to be rounded up, but your question can also be interpreted such that 1.01 has to be rounded down. (If the latter is what you want, look at Peter Lawrey's answer.)
For doubles (and floats) Java provides the standard method Math.ceil(double a) for the ceil function.
For BigDecimal values you can use the setScale method: set the scale to 0 (no decimal fraction) and the rounding mode to RoundingMode.CEILING to specify how to round:
static BigDecimal ceil(BigDecimal a) {
return a.setScale(0, RoundingMode.CEILING);
}
My question may seem simple, but still can not get something that works.
I need to customize the Math.round rounding format or something to make it work as follows:
If the number is 1.6 he should round to 1, if greater than or equal to 1.7 should round to 2.0 . And so to all other decimal results with # .6
The way I'm doing the 1.6 being rounded to 2 shall be rounded to 1.
How can I do that?
Thank you!
Simply do this:
double threshold = 0.7;
Math.round(x - threshold + 0.5);
You could write a method that takes a double variable as input and returns the integer based on the first digit after the point. For instance, you could convert the input to a String and delimit it at the decimal point. Then check if the first digit after the point is less or greater than 6.
Math.floor(x + 0.6);
It possibly may solve your question.
I have the following code:
int i = (int) 0.72;
System.out.println(i);
Which yields the following output:
0
I would of imagined that the variable i should have the value of 1 (since 0.72 > 0.5 => 1), why is this not the case?
(I imagine that when casting to int, it simply cuts of the decimal digits after the comma, not taking into account of rounding up; so I'll probably have to take care of that myself?)
Correct, casting to an int will just truncate the number. You can do something like this to get the result you are after:
int i = (int)Math.round(0.72);
System.out.println(i);
This will print 1 for 0.72 and 0 for 0.28 for example.
Because when you cast a double to int, decimal part is truncated
UPDATE Math.round will give your desired output instead of Math.ceil:
System.out.println(Math.round(0.72));
// will output 1
System.out.println(Math.round(0.20));
// will output 0
You can use Math.ceil :
System.out.println(Math.ceil(0.72));
// will output 1
System.out.println(Math.ceil(0.20));
// will output 1
Casting to an int implicity drops the decimal part. That's why you get 0 because anything after the 0 is removed (in your case the 72). If you want to round then look at Math.round(...)
Explicit cast does a conversion a float/double value to an int variable (which discards the fractional part)
Java does not round-off the number like we do.It simply truncates the decimal part.
If you want to round-off the number use java.lang.Math
Casting double to int truncates the non-integer portion of the number.
To round numbers as you describe, use Math.round()
As a complete Java beginner, and just in case my experience is useful to someone, I was just making the following mistake:
int x = (int) Math.random() * 10;
... which will always set x to 0. Instead, I should've done int x = (int) (Math.random() * 10);.
Not much of a Java-know-how specific mistake, but I'll just throw this in case anyone puzzled by this stumbles upon this question.
how to keep only 3 value after point in BigDecimal ?
i found a solution but it requirt a RoundingMode
BigDecimal d = BigDecimal.valueOf(0.5649);
System.out.println(d.remainder(BigDecimal.ONE));
System.out.println(d.remainder(BigDecimal.ONE).divide(BigDecimal.valueOf(1), 3, RoundingMode.CEILING));
i want to keep a number exact without rounding.
Just use setScale and RoundingMode.DOWN
Rounding mode to round towards zero. Never increments the digit prior
to a discarded fraction (i.e., truncates).
for example
BigDecimal.valueOf(0.5649).setScale(3, RoundingMode.DOWN)
BigDecimal isn't intended to be used with such limitations. Only ever wanting 3 decimals is a strange requirement. Maybe you only want to present 3 decimals to the users?
If so I suggest using: java.text.DecimalFormat
If you really want to make sure that you never do calculations with higher precission than 3 decimals I suggest making your own reprensentation/class. Internally you hold the value as a long (or appropriate class/primitive) but at a value 1000 times the actual value. All calculations are done with the internal reprensentation and when asked for a value, divide the internal value with 1000.0d and convert to double (or appropriate) and return.
I would use double for this.
double d = 0.5649;
d = (long) (d * 1000) / 1000.0; // round down.
System.out.println(d);
prints
0.564
or
d = (long) (d * 1000 + 0.5) / 1000.0; // round half up.