html/template 未显示精确小数位带有 e+07 表示法的浮点值

met*_*ata 5 floating-point go go-templates

我正在尝试一个示例,其中我将一个值传递1.8e+07TestValstruct 的字段Student。现在我希望这个1.8e+07值精确到小数位,但它没有这样做。如果值为 ,则能够以精确的小数位 ( 180000) 显示该值1.8e+05。但如果大于e+05则无法显示。

例子

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)
    }
}

Run Code Online (Sandbox Code Playgroud)

请帮忙。

icz*_*cza 4

这只是浮点数的默认格式。的包文档fmt对此进行了解释:%v动词是默认格式,对于浮点数意味着/恢复%g

%e对于大指数,%f否则。下面讨论精度。

如果您不想要默认格式,请使用printf模板函数并指定您想要的格式,例如:

{{printf "%f" .TestVal}}
Run Code Online (Sandbox Code Playgroud)

这将输出(在Go Playground上尝试):

Hello AJ, value is 18000000.000000
Run Code Online (Sandbox Code Playgroud)

或者使用:

{{printf "%.0f" .TestVal}}
Run Code Online (Sandbox Code Playgroud)

它将输出(在Go Playground上尝试):

Hello AJ, value is 18000000
Run Code Online (Sandbox Code Playgroud)

参见相关:

在golang html/template中设置浮动格式