简体   繁体   中英

Rounding to 3 decimal places in a distance formula

I have a double that I need rounded to 3 decimal places. I'm not sure how to accurately implement Math.Round. This is what I have so far:

double distance= Math.Sqrt(deltax + deltay);
Math.Round((decimal)distance, 3);
Console.WriteLine("Distance :" + distance);

Don't round it using Math.Round() , round it in the output string formatter:

double distance = Math.Sqrt(deltax + deltay);
Console.WriteLine("Distance :{0:f3}", distance);

You almost never want to use Math.Round() for formatting output.

The reason is, if you are formatting output to 3 decimal places, you normally want to show trailing zeros to indicate how many DPs you are displaying.

For example, given

double x = 0.1;

Then

double rounded = Math.Round(x, 3);
Console.WriteLine(rounded);

will display 0.1 , whereas

Console.WriteLine("{0:f3}", x);

will display 0.100 , which instantly tells the user that it was rounded to 3 dps.

If you want to remove trailing zeroes from the output, then you could use Math.Round() , but I'd use the ### string formatter:

Console.WriteLine("{0:0.###}", x);

This will ouput 1.2345 as 1.235 and 1.0 as 1 .

Use the return value of Math.Round (already noted by Uwe Keim ) and remove the decimal cast.

double distance = Math.Sqrt(10.438295 + 10.4384534295);
Console.WriteLine("Distance :" + Math.Round(distance, 3));

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