Categories:
.NET (357)
C (330)
C++ (183)
CSS (84)
DBA (2)
General (7)
HTML (4)
Java (574)
JavaScript (106)
JSP (66)
Oracle (114)
Perl (46)
Perl (1)
PHP (1)
PL/SQL (1)
RSS (51)
Software QA (13)
SQL Server (1)
Windows (1)
XHTML (173)
Other Resources:
How do I round numbers?
How do I round numbers?
✍: Guest
The simplest and most straightforward way is with code like
(int)(x + 0.5)
C's floating to integer conversion truncates (discards) the fractional part, so adding 0.5 before truncating arranges that fractions >= 0.5 will be rounded up. (This technique won't work properly for negative numbers, though, for which you could use something like (int)(x < 0 ? x - 0.5 : x + 0.5), or play around with the floor and ceil functions.)
You can round to a certain precision by scaling:
(int)(x / precision + 0.5) * precision
Handling negative numbers, or implementing even/odd rounding, is slightly trickier.
Note that because truncation is otherwise the default, it's usually a good idea to use an explicit rounding step when converting floating-point numbers to integers. Unless you're careful, it's quite possible for a number which you thought was 8.0 to be represented internally as 7.999999 and to be truncated to 7.
2015-06-26, 1887👍, 0💬
Popular Posts:
What are the two kinds of comments in JSP and what's the difference between them? <%-- JSP Co...
What is COCOMO I, COCOMOII and COCOMOIII? In CD we have a complete free PDF tutorial of how to prepa...
How To Truncate an Array? - PHP Script Tips - PHP Built-in Functions for Arrays If you want to remov...
Write out a function that prints out all the permutations of a string. For example, abc would give y...
What is the significance of Finalize method in .NET? .NET Garbage collector does almost all clean up...