Skip to content

Commit ded2ec3

Browse files
committed
prec handling
1 parent cb5fcde commit ded2ec3

3 files changed

Lines changed: 29 additions & 3 deletions

File tree

sprint_test.go

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -26,6 +26,10 @@ func TestSprint(t *testing.T) {
2626
1023,
2727
"1.00kB",
2828
},
29+
{
30+
999.5,
31+
"0.98kB",
32+
},
2933
{
3034
1024 + 512,
3135
"1.50kB",

value.go

Lines changed: 10 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -14,6 +14,7 @@ func (v Value) String() string {
1414

1515
func (v Value) Format(f fmt.State, verb rune) {
1616
var wid, prec int
17+
userPrec, hasUserPrec := f.Precision()
1718
var scale rune
1819
divisor := Value(1024.0)
1920
sign := byte(0)
@@ -44,7 +45,13 @@ func (v Value) Format(f fmt.State, verb rune) {
4445
sign = '+'
4546
}
4647

47-
if v >= 1000 {
48+
scaleAt := Value(1000)
49+
if !hasUserPrec {
50+
// With default precision (0), 999.5 rounds to 1000.
51+
scaleAt = 999.5
52+
}
53+
54+
if v >= scaleAt {
4855
for _, scale = range "kMGTPEZYRQ" {
4956
v /= divisor
5057
if v < 10 {
@@ -67,8 +74,8 @@ func (v Value) Format(f fmt.State, verb rune) {
6774
if n, ok := f.Width(); ok {
6875
wid = n
6976
}
70-
if n, ok := f.Precision(); ok {
71-
prec = n
77+
if hasUserPrec {
78+
prec = userPrec
7279
}
7380

7481
var buf []byte

value_test.go

Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -55,6 +55,21 @@ func TestValue_Format(t *testing.T) {
5555
f: "%b",
5656
v: 1,
5757
},
58+
{
59+
name: "0.98kB",
60+
f: "%v",
61+
v: 999.5,
62+
},
63+
{
64+
name: "-0.98kB",
65+
f: "%v",
66+
v: -999.5,
67+
},
68+
{
69+
name: "1000B",
70+
f: "%.0v",
71+
v: 999.5,
72+
},
5873
{
5974
name: "1.0 ",
6075
f: "%#-5.1v",

0 commit comments

Comments
 (0)