Search code examples
gofloating-pointgo-templates

html/template is not showing a float value with e+07 notation in exact decimal places


I'm trying an example where I'm passing a value 1.8e+07 to the TestVal field of struct Student. Now I want this 1.8e+07 value to be in exact decimal places but it is not doing so. It is able to show the value in exact decimal places(180000) if the value is 1.8e+05. But if it is greater than e+05 then it is unable to show it.

Example

package main

import (
    "fmt"
    "os"
    "text/template"
    
)

// declaring a struct
type Student struct {
    Name  string
    TestVal float32
}

// main function
func main() {

    std1 := Student{"AJ", 1.8e+07}

    // "Parse" parses a string into a template
    tmp1 := template.Must(template.New("Template_1").Parse("Hello {{.Name}}, value is {{.TestVal}}"))

    // standard output to print merged data
    err := tmp1.Execute(os.Stdout, std1)

    // if there is no error,
    // prints the output
    if err != nil {
        fmt.Println(err)
    }
}

Please help.


Solution

  • That's just the default formatting for floating point numbers. The package doc of fmt explains it: The %v verb is the default format, which for floating numbers means / reverts to %g which is

    %e for large exponents, %f otherwise. Precision is discussed below.

    If you don't want the default formatting, use the printf template function and specify the format you want, for example:

    {{printf "%f" .TestVal}}
    

    This will output (try it on the Go Playground):

    Hello AJ, value is 18000000.000000
    

    Or use:

    {{printf "%.0f" .TestVal}}
    

    Which will output (try it on the Go Playground):

    Hello AJ, value is 18000000
    

    See related:

    Format float in golang html/template