英文:
html/template is not showing a float value with e+07 notation in exact decimal places
问题
我正在尝试一个示例,其中我将值1.8e+07
传递给结构体Student
的TestVal
字段。现在我希望这个值1.8e+07
以精确的小数位显示,但实际上并没有这样做。如果值是1.8e+05
,它可以以精确的小数位(180000
)显示该值。但如果大于e+05
,它就无法显示。
示例代码如下:
package main
import (
"fmt"
"os"
"text/template"
)
// 声明一个结构体
type Student struct {
Name string
TestVal float32
}
// 主函数
func main() {
std1 := Student{"AJ", 1.8e+07}
// "Parse"将字符串解析为模板
tmp1 := template.Must(template.New("Template_1").Parse("Hello {{.Name}}, value is {{.TestVal}}"))
// 标准输出打印合并的数据
err := tmp1.Execute(os.Stdout, std1)
// 如果没有错误,则打印输出
if err != nil {
fmt.Println(err)
}
}
请帮忙看看。
英文:
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.
答案1
得分: 4
这只是浮点数的默认格式。fmt
包的文档解释了这一点:%v
是默认格式,对于浮点数来说,它会转换为 %g
,也就是
> 对于大指数使用 %e
,否则使用 %f
。精度在下面有详细讨论。
如果你不想使用默认格式,可以使用 printf
模板函数并指定你想要的格式,例如:
{{printf "%f" .TestVal}}
这将输出(在 Go Playground 上试一试):
你好 AJ,值为 18000000.000000
或者使用:
{{printf "%.0f" .TestVal}}
这将输出(在 Go Playground 上试一试):
你好 AJ,值为 18000000
参考链接:
https://stackoverflow.com/questions/41159492/format-float-in-golang-html-template/41159739#41159739
英文:
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:
https://stackoverflow.com/questions/41159492/format-float-in-golang-html-template/41159739#41159739
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论