string xyz = "23.659";
return string.Format("{0:F"+2+"}", xyz);
output = 23.66
When I use string.format the value gets rounded off, but I need 23.65 as the output. How to prevent rounding off in string.format?
string xyz = "23.659";
return string.Format("{0:F"+2+"}", xyz);
output = 23.66
When I use string.format the value gets rounded off, but I need 23.65 as the output. How to prevent rounding off in string.format?
You can round the value manually, e.g. with a help of Math.Round:
// If you have string (not decimal or double) we'll have parse
string xyz = "23.659";
return double.TryParse(xyz, out var value)
? string.Format("{0:F2}", Math.Round(value, 2, MidpointRounding.ToZero))
: xyz;
If xyz
is of type float
, double
, decimal
which is more natural the code doesn't want parsing:
double xyz = 23.659;
return string.Format("{0:F2}", Math.Round(xyz, 2, MidpointRounding.ToZero));