我需要导出金额默认保留 2 位小数的 json。
在查询中我使用了“从产品中选择格式(金额,2)”
type product struct {
Amount float32 `db:"Amount"`
}
所以我需要如果金额值为 99,则应导出 99.00 每次都返回 99.
我只是简单地从数据库检索数据并像 json marshal 一样导出动态产品结构。 从数据库中,我得到了十进制格式的值,但是当我们在结构中分配值时,小数点会丢失。
注意:: fmt.Sprintf("%.2f", value) 不起作用。
要导出 99.00 而不是 99 ,您可以将金额值从 int 转换为具有指定小数位数的 float。这是具有相同逻辑的简单代码:
package main
import (
"fmt"
)
func main() {
amount := 99
var desiredVal float64 = float64(amount)
fmt.Printf("amount = %d \n", amount)
fmt.Printf("\nnew amount= %.2f", desiredVal)
}
输出:
amount = 99
new amount= 99.00
如上所述,格式化需要在客户端完成 - 这样才有意义。
尽管如此,这里有一个解决方法 - 只需使用格式化值创建另一种类型,然后对其进行封送:
package main
import (
"encoding/json"
"fmt"
)
type product struct {
Amount float32
}
func main() {
p := product{Amount: 99.00}
fmt.Println(string(marshal(p)))
}
type N struct {
Amount string
}
func NewN(p product) N {
return N{
Amount: fmt.Sprintf("%.2f", p.Amount),
}
}
func marshal(p product) []byte {
n := NewN(p)
r, _ := json.Marshal(&n)
return r
}
{"Amount":"99.00"}
一种解决方案是分配一些不可能的值,例如 7777.777,然后编组该结构。然后对编组字符串进行字符串替换,即用 99.00 替换 7777.77。
有类似的问题,我可以使用 JSON 编码器解决
json.Number
。
type Trans struct {
Amount float64 `json:"amount"`
Date string `json:"date,omitempty"`
Order int `json:"order"`
Label string `json:"weekLabel,omitempty"`
}
func (t Trans) MarshalJSON() ([]byte, error) {
return json.Marshal(struct {
Amount json.Number `json:"amount"`
Date string `json:"date,omitempty"`
Order int `json:"order"`
Label string `json:"weekLabel,omitempty"`
}{
Amount: json.Number(fmt.Sprintf("%.2f", t.Amount)),
Date: t.Date,
Order: t.Order,
Label: t.Label,
})
}