Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Bytes returns 32 MB for 31450000 bytes instead of 31 MB #103

Open
ravibitsgoa opened this issue Apr 5, 2022 · 2 comments
Open

Bytes returns 32 MB for 31450000 bytes instead of 31 MB #103

ravibitsgoa opened this issue Apr 5, 2022 · 2 comments

Comments

@ravibitsgoa
Copy link

Sample program

package main

import (
	"fmt"
	"github.com/dustin/go-humanize"
)

func main() {
	fmt.Println(humanize.Bytes(31350000))
	fmt.Println(humanize.Bytes(31450000))
}

Current output

The above program, compiled with the latest main branch prints 31 MB and 32 MB.

Expected output

The result should be 31 MB for both calls. This is because 31.45 is less than 31.5. Hence, should be rounded down.
This could be happening because of rounding errors in floating points.

Also, as a side note, the default rounding behaviour of the Bytes function is not documented properly.

@dustin
Copy link
Owner

dustin commented Apr 6, 2022

Yeah, that makes sense. It's a floor as it goes up in magnitude, so it wouldn't use a rounding rule like you expect. I'm not sure there's a best way. It's easy to argue for any of floor, ceiling, or the many rounding variations.

@ravibitsgoa
Copy link
Author

ravibitsgoa commented Apr 6, 2022

If I understood correctly, we should use floor, right?
So humanize.Bytes(31450000) should be 31 MB right?
Shall I raise a PR to fix this bug?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants