How can I prevent rounding of decimal places?

I use C #, every time I insert 3 decimal places, the number is rounded, for example.

1,538

rounds

up to 1.54

I want the number to be like, for example, 1.53 (up to two decimal places, without rounding).

How can i do this?

+6
c #
source share
2 answers

I believe you want to use Math.Truncate()

 float number = 1.538 number = Math.Truncate(number * 100) / 100; 

Truncate will snatch the final bit. However, remember to be careful with negative numbers.

It depends on whether you always want to round to 0 or just complete the end, Math.Floor always rounds to negative infinity. Here is a message about the difference between the two.

+6
source share

Found this link that gives a nice piece of code so that you can specify the decimal numbers you want, e.g. Math.Round ().

Mainly: -

 public static double Floor(this double d, int decimals) { return Math.Floor(d * Math.Pow(10, decimals)) / Math.Pow(10, decimals); } 
+3
source share

All Articles