简体   繁体   中英

How Can I Prevent Rounding Decimals?

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

1.538

rounds

to 1.54

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

How can i do it?

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.

Found this link which gives a good code snippet to allow you to specify the number decimals places you want like Math.Round() allows.

Basically it's this:-

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM