Java - unexpected result when rounding a double/float to 2 decimals - java

I encounter a problem when round a double to 2 decimals. I know this questions have been asked in many places. But my question is slightly different and I cannot find it in other places.
So far as I know, there are 2 ways to do this.
Math.round(double*100.0)/100.0
DecimalFormat(“###.##”)
I am trying to use the first way: a custom way to round double.
When the second decimal is 0, the result will only print the first decimal and ignore the second one.
For example,
Math.round(1.23333*100.0)/100.0 The result is 1.23. This works good.
Math.round(3.90*100.0)/100.0. The result is 3.9. Problem occurs. I want to show 3.90 instead of 3.9
Math.round(3*100.0)/100.0. The result is 4.0. I want 4.00 instead of 4.0
So, my question is that how I can have a double value with 2 decimals no matter if the last decimal is 0 or not. I know I can use the second way- DecimalFormat(“###.##”) to achieve what I want! But is it possible to do it by using the first way?
Edit: Thanks for the answers. It looks like it is NOT possible to use the round() method to achieve it. However, some people suggest to use the combination of 2 ways to achieve it. But I think using only DecimalFormat(“###.##”) can get what I want. Can anyone confirm it?

I would suggest using String.format("%1$.2f",x). It rounds the value to the specified precision (2 digits in our example) and leaves the trailing zeros on the right.
System.out.println(String.format("%1$.2f",3.121)) gives 3.12
System.out.println(String.format("%1$.2f",3.129)) gives 3.13
System.out.println(String.format("%1$.2f",3.12)) gives 3.12
System.out.println(String.format("%1$.2f",3.10)) gives 3.10

Have you tried the following?
DecimalFormat(“###.00”)
If not mistaken, trailing zeros are left blank when using the #-sign.

I believe you need to use a combination of both to achieve your needs.
The rounding to obtain a number with two decimals, and the DecimalFormat to display it with two decimals.

You should be formatting your result with DecimalFormat
DecimalFormat format = new DecimalFormat("0.00");
System.out.println(Math.round(3.90*100.0)/100.0); // 3.9
System.out.println(format.format(Math.round(3.90*100.0)/100.0)); // after using format 3.90
System.out.println(format.format(Math.round(3*100.0)/100.0));
And the output is
3.9
3.90
3.00

Related

format numbers in java to remove decimals and add decimals

I am looking at Java code which will perform following two operations:-
If I am sending value 10.00, my method should format it to 1000 and
If I am getting 1000 in response from 3rd party system, I need to convert 1000 to 10.00 in my another method. Simply whatever decimal value (2 digit's after decimal) I'm sending need to remove decimals and whatever Non-decimal Value I'm receiving need to convert to decimals (2 digits after decimals)
I tried to write the code but it's not working expected. Can anyone please guide me? I'm using JDK 7.
You were supposed to provide your own code which doesn't work, so we can help you figure it out and make it work, not posting a problem and let us do all the work.
Input string and convert it to char array with toCharArray() method. Rewrite the array without the dot for the first part. For the second part do the same thing except you insert dot on position you want.
BTW your question is not clear enough, how does the algorithm work, what happens if you get number 15, or 1555...does it translate to 0.15 and 15.55?

How do You Find the Number of Places After the Decimal Point with BigDecimal?

I'm trying to use BigDecimals to calculate something and then round to 5 decimal places if it has more than that. How can I do this?
Would scale() work?
Did you already crawl through JavaDoc, especially the function precision()?
And this here might be a direct solution which makes it needless to check the precision first:
yournumber.round(new MathContext(5, HALF_UP));
And after that use stripTrailingZeros() (thx to #GregKopff)

How to round a float number in Java if its a whole? [duplicate]

This question already has answers here:
How to round a number to n decimal places in Java
(39 answers)
Closed 8 years ago.
How do I round a float number if it returns a whole value? And, how do I round if it's like:
5/2 = 2.5
and NOT like this:
5/2 = 2.50000000
A double does not allow you to specify the number of decimal places it has; you may be able to set as many as you wish to 0, but they are still there. (Note that, mathematically, the two values you show for 5/2 are the same.) What you can do is control how many get displayed; since you haven't specified how you are attempting to display this value, I can't help in how to modify it to limit the number of decimal places to show.
Whenever needed, you can make some modifications on your double, such as using the setRoundingMode method of DecimalFormat class, along with the RoundingMode enum.
As mentioned before though, 2.5 is the same with 2.500000 in a double, you do not have to change its digits.
I guess you are trying to print your double and you get a number of unwanted digits in the output. In that case, I suggest though that you convert your double into a formatted string and use it as such:
System.out.println(String.format("%.2f", myDouble));
You are a bit confused I think...
2.5 and 2.50000000 are the exact same thing!
They are just written differently.
I don't really understand what you are trying to achieve but you can round floats like this:
float result = Math.round(someFloat);
If you always want to round up or down regardless of what the number is use:
float result = (float)Math.ceil(someFloat);
or
float result = (float)Math.floor(someFloat);

Unify 10^x power in a sequence of number

I have a sequence of numbers like this:
1.687155E21
3.981457E19
0.5532155E21
3.018843E21
2.0532155E21
4.5532155E21
3.1637913E19
My problem is how to convert the two numbers which ends with 10^19 to be like the others (10^21). Because after this unification i need to trunc the number to print only something like 3.5.
In C/C++ i know how to work with precision, but in Java I haven't got any idea.
Divide all your number by / 1e19, round to as many decimal digits you want:
168.7155
3.981457
55.32155
301.8843
205.32155
455.32155
3.1637913
Use the Formatter Class to bring them into the desired scientific notation (java.util.Formatter)
I'd suggest something similar as Tomasz Nurkiewicz did, but instead of dividing by 1E19 divide by 1E21, convert them to strings with the required precision using Formatter (see the comment of count0) but not as scientific format, but as a general one. In the end just add E21 to those strings. In the end you should get (I hope, I got the idea correctly)
1.687155E21
0.03981457E21
0.5532155E21
3.018843E21
2.0532155E21
4.5532155E21
0.031637913E21
Can't you just multiply the E19 numbers by 10 ^ 2 = 100?
After they have been normalized to E21, you should be able to divide all of them by 10^21 (if they're floats), and they will all be in the range of 0-9.999...

Rounding off in java

I have a list that contains many decimal values.
If i get a value of .032 i have to
round it off to 3.2%
If i get a value
of 32.33 i have to round it off to
32%
If i get a value of 32.66 i have to round it off to 33%
if decimal digit is 5,6,7,8 or 9
round up to the next
how should i go bt dng this?
Use Math.round(). This correctly rounds a number upwards if the fractional part is 0.5 or greater.
If I understood you question correctly:
For the first point, you can use DecimalFormat class, see API
I'm not sure why you'd want to "round" 32.33 -> 32% as this is not rounding. If you are parsing user input data which could be given in this way, you can divide by 100 (giving 0.3233) and use DecimalFormat.
For the others you can use Math.round() as adviced below/above
Math.round() and convert it to percent form.
I doubt about .032 case. rest are looking good.
Use MathUtils (Apache Commons Math)
MathUtils.round(double, scale, roundingMethod);
scale - The number of digits to the right of the decimal point. (+/-)
roundingMethod : BigDecimal.ROUND_DOWN, #.ROUND_CEILING, #.ROUND_HALF_UP, ...

Categories