将"decimal.NullDecimal"类型强制转换为int



我正在使用一个类型为decimal.NullDecimal(来自github.com/shopspring/decimal(的变量,并希望强制转换其整数值,以便能够将其与整数进行比较。我应该如何转换它的十进制值
这是我的代码:

import (
// other packages
"github.com/shopspring/decimal"
)
type BooksStores struct {
PublisherShare decimal.NullDecimal `json:"publisher_share"`
}
var booksStores BooksStores
err := c.ShouldBindBodyWith(&booksStores, binding.JSON)
if err != nil {
c.JSON(http.StatusUnprocessableEntity, gin.H{
"error": err.Error(),
})
return
}
publisherShare := booksStores.PublisherShare

// Here I want to compare the `publisherShare` value with 0 and 100
if publisherShare < 0 || publisherShare > 100 {
// DO SOMETHING
}

以下是我尝试过的,但都没有成功:


import "https://github.com/spf13/cast"

cast.ToInte(publisherShare) 
cast.ToInte(&publisherShare)
cast.ToInt(publisherShare.Decimal)
cast.ToInt(publisherShare.Decimal)
// but it is casted to zero, I have to use `decimal.NullDecimal` type
// due to the database considerations (later I have to update something)

我认为我应该在github.com/shopspring/decimal包上使用Cmp方法来比较publisherShare值和数字。

由于并非所有任意精度的小数都可以表示为Go整数,我认为您可能应该使用decimal.NewFromInt(...)将int转换为小数,然后使用类似decimal的东西进行比较。大于:

package main
import (
"fmt"
"github.com/shopspring/decimal"
)
func main() {
// Let's say dec is the decimal we want to compare
dec := decimal.NewFromInt(42)
// We compare it to 100
h := decimal.NewFromInt(100)
if dec.GreaterThan(h) {
fmt.Println("> 100")
} else {
fmt.Println("<= 100")
}
}

游乐场链接


请注意,decimal.NullDecimal只包含一个Decimal和一个有效性标志,因此一旦您知道它是有效的,您只需从中获取Decimal字段,然后进行比较,如上所示。

好的,现在问题解决了,我应该使用var booksStores *BooksStores而不是var booksStores BooksStores

type BooksStores struct {
PublisherShare decimal.NullDecimal `json:"publisher_share"`
}
var booksStores *BooksStores // Here is the place I had to change
err := c.ShouldBindBodyWith(&booksStores, binding.JSON)
if err != nil {
c.JSON(http.StatusUnprocessableEntity, gin.H{
"error": err.Error(),
})
return
}
publisherShare := booksStores.PublisherShare
if publisherShare.Decimal.LessThan(decimal.NewFromInt(0)) || publisherShare.Decimal.GreaterThan(decimal.NewFromInt(100)) {
// DO SOMETHING
return
}

最新更新