Manjay_TBAG
Manjay_TBAG

Reputation: 2245

C# Why string.format round float values to nearest 10th?

Following number when formatted it rounds up to nearest 10th value

var testVal = Convert.ToSingle("10963798");
var formattedVal = string.Format("{0:n0}", testVal);

Output: 10,963,800

How can I avoid this round up?

Upvotes: 1

Views: 290

Answers (1)

Thomas
Thomas

Reputation: 181745

ToSingle returns a single-precision float, which doesn't have that kind of precision (just 7 decimal digits usually). For this reason, Format assumes that the last digit is imprecise, and rounds it to 0.

Use ToDouble instead, which returns a double.

Or, because you're not using any fractional part, just use ToInt32.

Upvotes: 3

Related Questions