-1

I am using %0.1f to round my float to 1 decimal places. However I am getting different results on rounding.

package main

import "fmt"

func format() {
    name := "Granth"
    age := 28
    fmt.Print("my name is ", name, " and my age is ", age, "\n")
    fmt.Printf("my name is %v and my age is %v\n", name, age)
    fmt.Printf("my name is %q and my age is %v\n", name, age)
    fmt.Printf("my name is %q and my age is %q\n", name, age)
    fmt.Printf("name type is %T and age type is %T\n", name, age)
    fmt.Printf("the float is %f\n", 34.55)
    fmt.Printf("the float rounded off is %0.1f\n", 35.55)
    fmt.Printf("the float rounded off is %0.1f\n", 25.55)
}

and the output is:-

my name is Granth and my age is 28
my name is Granth and my age is 28
my name is "Granth" and my age is 28
my name is "Granth" and my age is '\x1c'
name type is string and age type is int
the float is 34.550000
the float rounded off is 35.5
the float rounded off is 25.6

why is it showing 35.55 rounded as 35.5 and 25.55 rounded as 25.6?

go version go1.19.1 windows/amd64

Granth
  • 325
  • 4
  • 17

1 Answers1

1

None of your presentations provide all significant digits, and few decimal real values can be precisely represented in binary floating point used at the machine-level.

So if for example 35.55 were actually stored in binary floating point as something closer to say 35.55000000000001, it will become 35.6 when presented to one decimal place, whereas if 25.55 were more precisely 25.5499999999999, it would round to 25.5 when presented to one decimal place, and 25.55 to two.

To demonstrate this, display 25.55 to more decimal places. I am not familiar with go and it's handling if real number representation, but IEEE-754 double precision binary floating point can represent decimal real numbers to a precision of about 15 significant figures. So any imprecision will be evident after 15 significant figures.

Clifford
  • 88,407
  • 13
  • 85
  • 165