优化float包装类型的处理

This commit is contained in:
白茶清欢 2023-05-08 17:15:32 +08:00
parent 9ca35bf51b
commit a1748cc324

View File

@ -24,11 +24,17 @@ type Float float64
// Author : go_developer@163.com<白茶清欢> // Author : go_developer@163.com<白茶清欢>
// //
// Date : 14:36 2023/5/5 // Date : 14:36 2023/5/5
func (f Float) ToFloat32() (float32, error) { func (f Float) ToFloat32() Float32Result {
if f > math.MaxFloat32 || f < math.SmallestNonzeroFloat32 { res := Float32Result{
return 0, fmt.Errorf("float32 should between %v and %v", float32(math.SmallestNonzeroFloat32), float32(math.MaxFloat32)) Value: 0,
Err: nil,
} }
return float32(f), nil if f > math.MaxFloat32 || f < math.SmallestNonzeroFloat32 {
res.Err = fmt.Errorf("float32 should between %v and %v", float32(math.SmallestNonzeroFloat32), float32(math.MaxFloat32))
return res
}
res.Value = float32(f)
return res
} }
// ToFloat64 ... // ToFloat64 ...
@ -36,11 +42,17 @@ func (f Float) ToFloat32() (float32, error) {
// Author : go_developer@163.com<白茶清欢> // Author : go_developer@163.com<白茶清欢>
// //
// Date : 14:36 2023/5/5 // Date : 14:36 2023/5/5
func (f Float) ToFloat64() (float64, error) { func (f Float) ToFloat64() Float64Result {
if f > math.MaxFloat64 || f < math.SmallestNonzeroFloat64 { res := Float64Result{
return 0, fmt.Errorf("float32 should between %v and %v", float64(math.SmallestNonzeroFloat64), float64(math.MaxFloat64)) Value: 0,
Err: nil,
} }
return float64(f), nil if f > math.MaxFloat64 || f < math.SmallestNonzeroFloat64 {
res.Err = fmt.Errorf("float32 should between %v and %v", float64(math.SmallestNonzeroFloat64), float64(math.MaxFloat64))
return res
}
res.Value = float64(f)
return res
} }
// ToString ... // ToString ...
@ -48,10 +60,16 @@ func (f Float) ToFloat64() (float64, error) {
// Author : go_developer@163.com<白茶清欢> // Author : go_developer@163.com<白茶清欢>
// //
// Date : 14:38 2023/5/5 // Date : 14:38 2023/5/5
func (f Float) ToString() (string, error) { func (f Float) ToString() StringResult {
floatVal, err := f.ToFloat64() floatVal := f.ToFloat64()
if nil != err { if nil != floatVal.Err {
return "", err return StringResult{
Value: "",
Err: floatVal.Err,
}
}
return StringResult{
Value: fmt.Sprintf("%v", floatVal),
Err: nil,
} }
return fmt.Sprintf("%v", floatVal), nil
} }