Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C#: how to round an Integer to the nearest 1000 [duplicate]

How can i round an (int) so that a number like (22536) is equal to 22000 or 23000?

I haven't found a specific method in the Math class, Math.Round seems to round double only to the nearest int.

like image 309
fra pet Avatar asked Dec 05 '22 03:12

fra pet


1 Answers

By using modulus:

int x = 1500;

int result = x % 1000 >= 500 ? x + 1000 - x % 1000 : x - x % 1000;

It checks if x has any more than 499 when the thousands are stripped, and then rounds it.

like image 97
Patrick Hofman Avatar answered Dec 31 '22 07:12

Patrick Hofman