dotnet / dotnet/runtime

"0" format specifier rounds large floating point numbers weirdly.

Open
#120,979 4 comments 0 reactions 0 assignees View on GitHub
area-System.Numerics
Dominant language
C#
Stars
18.3k
Forks
5.6k
PR merge metrics
PR metrics pending

Description

### Description

I noticed that the "0" format specifiers will round large enough floating point numbers for seemingly no reason.
For example with 32 bit floats "16777216" becomes "16777220". Formats such as "F0" will print the number correctly.

### Reproduction Steps

Run the following code ([Try on SharpLab](https://sharplab.io/#v2:EYLgxg9gTgpgtADwGwBYA0AXEUCuA7NAExAGoAfAAQCYBGAWAChGAzAGwgEMMACN7gXm40kAdjG0kAbkaMKNAJwAKNgDoAKhADKGKAEs8Ac0UAiAGIAGYwEor0hnKWqN2vYZOWbkoA==))
```cs
using System;

float fl = 16777216;

Console.WriteLine(fl.ToString("F0"));
Console.WriteLine(fl.ToString("0"));
```

### Expected behavior

`16777216f.ToString("0")` prints out `16777216`

### Actual behavior

`16777216f.ToString("0")` prints out `16777220`

### Regression?

_No response_

### Known Workarounds

_No response_

### Configuration

_No response_

### Other information

_No response_

Contributor guide

Open the contributing guide

Research direction

Start at the float.ToString("0") entry point and compare its behavior with float.ToString("F0") using the reproduction values 16777216f and 16777220f. Add a regression test covering the expected exact output, then verify the existing formatting tests pass.

Written by the indexing model from the issue text.

Assessment

Tech stack
csharp
Domain
tooling
Issue type
Bug
Difficulty
3/5
Estimated time
1-2 days
Activity status
Quiet
Clarity
Mostly clear
Newbie friendliness
55/100

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.