Click here to Skip to main content
15,868,016 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Hi,
I have a problem, in my project I have a List<polyline>() and in it the Polylines have a Length property. I would like to round all Polyline in List to 5 places.

What I have tried:

listPolyline = listPolyline.Select(x => Math.Round(x => x.Length, 5)).ToList();

I thought it would go something like this.

Does anyone know how to do this?

Thank you in advance for your reply

David
Posted
Updated 1-Dec-22 23:19pm

That's ... complicated.
Rounding to "5 places" isn't really something you can do with float or double values, because they aren't stored as decimal values, there there isn't a "one-to-one" mapping from the binary representation of a floating point decimal value to the internal binary data the system uses. This may help you understand: Single-precision floating-point format - Wikipedia[^] as may this: Why Floating-Point Numbers May Lose Precision | Microsoft Learn[^]

As a general rule, if you want to display 5 significant digits in a floating point number, use a format specification when you convert it to a string for display rather than trying to round it to a number of digits as a numeric value.
C#
double d = 123.456789012;
Console.WriteLine($"{d:###.####}");
 
Share this answer
 
To modify the items in a list, there's no need to create a new list. Just iterate over the items in the list and modify them.
C#
foreach (Polyline x in listPolyline)
{
    x.Value = Math.Round(x.Value, 5);
}
The only complication comes if you're using a struct; if you are, then any changes you make will apply to a copy of the struct, and not the value in the list. You would need to update the list with the modified value:
C#
for (int index = 0; index < listPolyline.Count; index++)
{
    Polyline x = listPolyline[index];
    x.Value = Math.Round(x.Value, 5);
    listPolyline[index] = x;
}
Structure types - C# reference | Microsoft Learn[^]
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900