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

%.2f exception #40648

Closed
w22296437978 opened this issue Aug 8, 2020 · 5 comments
Closed

%.2f exception #40648

w22296437978 opened this issue Aug 8, 2020 · 5 comments

Comments

@w22296437978
Copy link

@w22296437978 w22296437978 commented Aug 8, 2020

image

@robpike
Copy link
Contributor

@robpike robpike commented Aug 8, 2020

The printed result is correct due to rounding. 0.505 will be rounded up to 0.51. The print routines round, they don't truncate.

Just for fun, I tried it in C as well, and printf("%.2f\n", 1823.505) prints 1823.51 in C too.

Working as intended.

@robpike robpike closed this Aug 8, 2020
@w22296437978
Copy link
Author

@w22296437978 w22296437978 commented Aug 8, 2020

由于四舍五入,打印结果正确。0.505将四舍五入为0.51。打印例行程序不会截断。

只是为了好玩,我也在C语言中进行了尝试,并且也在C语言中进行了printf("%.2f\n", 1823.505)打印1823.51

按预期工作。

but 2.445 => 2.44

@w22296437978
Copy link
Author

@w22296437978 w22296437978 commented Aug 8, 2020

image
How could this be?

@robpike
Copy link
Contributor

@robpike robpike commented Aug 8, 2020

To avoid bias, rounding a number ending in the digit 5 alternates between rounding up and rounding down, which means that overall all rounded numbers, half round up and half round down.

1 2 3 4 round down.
6 7 8 9 round up
5 rounds up half the time and down half the time.

See this program:

package main

import (
	"fmt"
)

func main() {
	for _, x := range ([]float64{0.005, 0.015, 0.025, 0.035, 0.045, 0.055, 0.065, 0.075, 0.085, 0.095}) {
		fmt.Printf("%.2f\n", x)
	}
}

which prints

0.01
0.01
0.03
0.04
0.04
0.06
0.07
0.07
0.09
0.10
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Linked pull requests

Successfully merging a pull request may close this issue.

None yet
3 participants
You can’t perform that action at this time.