英文:
Golang default return 2 decimal places
问题
我需要将 JSON 导出为默认的两位小数的金额。
在查询中,我使用了 "SELECT FORMAT(amount, 2) from product"。
type product struct {
Amount float32 `db:"Amount"`
}
所以,如果 Amount 的值是 99,它应该导出为 99.00,但每次都只返回 99。
我只是简单地从数据库中检索数据,并像 json.Marshal 一样导出动态的 product 结构体。
从数据库中获取的是带有小数格式的值,但在将值分配给结构体时,小数部分丢失。
注意:fmt.Sprintf("%.2f", value) 不起作用。
英文:
I need to export the json with default 2 decimal places for amount.
In Query i have used "SELECT FORMAT(amount, 2) from product"
type product struct {
Amount float32 `db:"Amount"`
}
So i need if the Amount value is 99 it should export 99.00
every time it is returning 99.
I just simply retrieving data from DB and exporting like json marshal the dynamic product struct.
From DB i am getting with decimal formatted value but the decimal getting lost when we are assigning the value in struct.
NOTE :: fmt.Sprintf("%.2f", value) will not work.
答案1
得分: 1
要将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
英文:
To export 99.00 instead of 99 ,you can convert the amount value from int to float with specified number of decimal points.Here is a simple code with the same logic :
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)
}
Output:
amount = 99
new amount= 99.00
答案2
得分: 0
如上所述,格式化需要在客户端完成 - 这样做是有道理的。
不过,这里有一个解决方法 - 只需创建另一种带有格式化值的类型,并进行编组:
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"}
英文:
As stated above, the formatting needs to be done on the client side - it make sense that way.
Nevertheless here is a workaround - just create a another type with the formatted values, and marshal it:
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"}
答案3
得分: 0
一种解决方案是将一些不太可能的值分配给结构体,比如7777.777,然后进行结构体的编组。然后对编组后的字符串进行替换,即将7777.777替换为99.00。
英文:
One solution is to assign some improbable value like 7777.777 and then marshal the structure. Then do a string replace of the marshalled string i.e., replace 7777.77 with 99.00.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论