Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How Can I Prevent Rounding Decimals?

Tags:

c#

.net

I'm using c#, every time i insert 3 decimal places, the number gets rounded e.g.

1.538

rounds

to 1.54

I want the number to be as is e.g. 1.53 (to two decimal places only without any roundings).

How can i do it?

like image 313
user311509 Avatar asked Jul 02 '10 17:07

user311509


1 Answers

I believe you want to use Math.Truncate()

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

Truncate will lop off the end bit. However, bear in mind to be careful with negative numbers.

It depends on whether you always want to round towards 0, or just lop off the end, Math.Floor will always round down towards negative infinity. Here's a post on the difference between the two.

like image 109
Armstrongest Avatar answered Sep 28 '22 00:09

Armstrongest