Round a double to 2 decimal places

Here’s an utility that rounds (instead of truncating) a double to specified number of decimal places. For example: Original version; watch out with this This breaks down badly in corner cases with either a very high number of decimal places (e.g. round(1000.0d, 17)) or large integer part (e.g. round(90080070060.1d, 9)). Thanks to Sloin for pointing this out. I’ve been using the above to round … Read more

Round a double to 2 decimal places [duplicate]

Here’s an utility that rounds (instead of truncating) a double to specified number of decimal places. For example: Original version; watch out with this This breaks down badly in corner cases with either a very high number of decimal places (e.g. round(1000.0d, 17)) or large integer part (e.g. round(90080070060.1d, 9)). Thanks to Sloin for pointing this out. I’ve been using the above to round … Read more

C++ string to double conversion

You can convert char to int and viceversa easily because for the machine an int and a char are the same, 8 bits, the only difference comes when they have to be shown in screen, if the number is 65 and is saved as a char, then it will show ‘A’, if it’s saved as … Read more

Converting double to integer in Java

is there a possibility that casting a double created via Math.round() will still result in a truncated down number No, round() will always round your double to the correct value, and then, it will be cast to an long which will truncate any decimal places. But after rounding, there will not be any fractional parts remaining. Here are the docs from Math.round(double): … Read more

Scanf/Printf double variable C

For variable argument functions like printf and scanf, the arguments are promoted, for example, any smaller integer types are promoted to int, float is promoted to double. scanf takes parameters of pointers, so the promotion rule takes no effect. It must use %f for float* and %lf for double*. printf will never see a float … Read more