Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# Rounding 2 decimals: Truncate vs Round

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?

like image 467
Ralph Avatar asked Jan 14 '23 05:01

Ralph


1 Answers

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 
like image 101
p.s.w.g Avatar answered Jan 15 '23 18:01

p.s.w.g