Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How do I force max 4 decimals without rounding up in C# / .NET

Example variables:

var example1 =  1,12345638282382384;
var example2 = 12,12;
var example3 = 30,19999;

Result what I want:

example1 = 1,1234;
example2 = 12,12; // 12,1200 would be better but isn't that important)
example3 = 30,1999;

What is the issue? I got more than 4 decimal numbers, but I want to only see 4 decimals. I search around the internet, but I only see examples of rounding up & full numbers getting a comma, while my example already have the comma’s.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

Furthermore, I am a student/junior developer and at least tried to search around before asking, hopefully someone knows the answer.

>Solution :

Math.Round allows you to specify the rounding behavior you want, eg Math.Round(example1,4,MidpointRounding.ToZero) produces 1.1234.

C# > var example1 =  1.12345638282382384;

C# > Math.Round(example1,4)
╭─✔──────────────────────────────────────────────────────────────╮
│ 1.1235                                                         │
╰────────────────────────────────────────────────────────────────╯
C# >  Math.Round(example1,4,MidpointRounding.ToZero)
╭─✔──────────────────────────────────────────────────────────────╮
│ 1.1234                                                         │
╰────────────────────────────────────────────────────────────────╯
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading