问题描述:

I would like to know which are the advantages and disadvantages using Truncate or Round when rounding a float to 2 decimals:

float number = 3.4567070

Math.Round(number, 2)

Math.Truncate(100 * number) / 100

Which is the best and eficent one? When to use round and when truncate?

网友答案:

Truncate is marginally more efficient, but these are very different functions.

  • Math.Round computes the nearest number to the input to a specified degree of accuracy.

    Rounds a value to the nearest integer or to the specified number of fractional digits.

  • Math.Truncate effectively discards the any digits after the decimal point. It will always round to the nearest integer toward zero.

    Calculates the integral part of a number

Which function you should use is entirely dependent on the logic you're trying to implement.

Here's a quick sample output of each function:

Input | Round | Truncate
------+-------+---------
 -1.6 |    -2 |       -1 
 -1.5 |    -2 |       -1 
 -1.4 |    -1 |       -1 
 -0.5 |     0 |        0 
  0.5 |     0 |        0 
  1.4 |     1 |        1 
  1.5 |     2 |        1 
  1.6 |     2 |        1 
网友答案:

That depends on your purpose. I don't think one is more effecient than the other. It's like saying "Should I use a nail or a screw?" They do different things.

网友答案:

If you are trying to round to 2 decimals, I highly recommend using Round() instead of Truncate(), if for no other reason than readability & maintainability. Your example is a bit confusing at first glance, and it takes some analysis to understand that it is effectively using some fancy footwork to get the Truncate() method to perform a rounding operation.

In general, when writing code, you should use the "correct" method first, and if benchmarking shows a performance issue, only then should you attempt optimizations such as your "tricky" code example.

相关阅读:
Top