优化字符串数字的处理
This commit is contained in:
parent
e8fc0addfc
commit
ab1f877b3c
@ -21,7 +21,8 @@ import (
|
||||
//
|
||||
// Date : 11:12 2024/3/8
|
||||
type DiffOption struct {
|
||||
StrictMode bool `json:"strict_mode"` // 采用严格模式: 1 != "1", 1 != 1.0 , 采用非严格模式 1 == "1", 1 == 1.0
|
||||
StrictMode bool `json:"strict_mode"` // 采用严格模式: 1 != 1.0 , 采用非严格模式 1 == 1.0
|
||||
AllowStringNumber bool `json:"allow_string_number"` // 是否允许字符串数字, 在非严格模式下, 若允许, 则 1 == "1" , 不允许, 则 1 != "1"
|
||||
IgnoreNotFoundField bool `json:"ignore_not_found_field"` // 忽略不存在的字段
|
||||
IgnoreEmptyString bool `json:"ignore_empty_string"` // 忽略空字符串, 若输入值为空字符串, 则不做比较, 认为两个值相同
|
||||
IgnoreZeroNumber bool `json:"ignore_zero_number"` // 忽略置为0的数字, 若输入的数据为数字类型, 则不做比较, 认为两个值相同
|
||||
@ -200,20 +201,24 @@ func DefaultDiffFunc(field string, inputVal wrapper.Map, storageVal wrapper.Map,
|
||||
// 存储值尝试转 float64
|
||||
inputValStr := fmt.Sprintf("%v", inputFieldVal)
|
||||
storageValStr := fmt.Sprintf("%v", storageFieldVal)
|
||||
var (
|
||||
storageFloat64 float64
|
||||
inputFloat64 float64
|
||||
)
|
||||
if err := util.ConvertAssign(&storageFloat64, storageValStr); nil == err {
|
||||
if err := util.ConvertAssign(&inputFloat64, inputValStr); nil == err {
|
||||
if storageFloat64 == inputFloat64 {
|
||||
return result
|
||||
}
|
||||
}
|
||||
}
|
||||
if inputValStr == storageValStr {
|
||||
return result
|
||||
}
|
||||
if option.AllowStringNumber {
|
||||
// 允许字符串数字
|
||||
var (
|
||||
storageFloat64 float64
|
||||
inputFloat64 float64
|
||||
)
|
||||
if err := util.ConvertAssign(&storageFloat64, storageValStr); nil == err {
|
||||
if err := util.ConvertAssign(&inputFloat64, inputValStr); nil == err {
|
||||
if storageFloat64 == inputFloat64 {
|
||||
return result
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// 浮点型数字. 去小数部分最右侧的0
|
||||
if inputFieldValType.Kind() == reflect.Float64 || inputFieldValType.Kind() == reflect.Float32 {
|
||||
inputValStrArr := strings.Split(inputValStr, ".")
|
||||
|
@ -43,6 +43,7 @@ func TestDefaultDiffFunc(t *testing.T) {
|
||||
assert.EqualValues(t, true, res.IsSame, "非严格模式下, float32与float64相等")
|
||||
res = DefaultDiffFunc("num3", input, storage, diffOption)
|
||||
assert.EqualValues(t, true, res.IsSame, "非严格模式下, float32与string相等")
|
||||
diffOption.AllowStringNumber = true
|
||||
res = DefaultDiffFunc("num4", input, storage, diffOption)
|
||||
assert.EqualValues(t, true, res.IsSame, "非严格模式下, float32与string相等")
|
||||
}
|
||||
|
Loading…
Reference in New Issue
Block a user