This week's book giveaway is in the NodeJS forum. We're giving away four copies of Serverless Applications with Node.js and have Slobodan Stojanovic & Aleksandar Simovic on-line! See this thread for details.
Just for practice, I'm writing a program that rounds a number to the nearest hundredth, but can't get the expected result. I'm trying to multiply a double value by 100, round it with Math.round(), then divide the entire result by 100 again to create a decimal rounded to the nearest hundredth. Instead, I get an integer value.
Math.round() returns a long or int, depending on the type of the argument. The expression 1.2345 * 100 consists of a double and int, respectively. By promotion rules, the 100 is turned into a double, 100.0. So the entire expression is a double. That means you'll be calling Math.round(double) and getting back a long, which you then divide by an int (100). By promotion rules, the result of that expression is a long. That long value gets promoted and assigned to the double variable.
If you just use a double value for the second 100, i.e., Math.round(1.2345 * 100) / 100.0 then you'll get the decimals you're expecting.
Note that in general, floating point operations are inherently imprecise and you won't always get exact decimals you expect if you use other numbers.