SafeFloatValue safely converts various types to float64 representation. This function provides a safe way to convert interface{} values to float64, handling multiple numeric types and string representations. It never panics and returns 0.0 for non-convertible values. Supported conversions: - float
(value interface{})
| 339 | // f := SafeFloatValue("123.45") // 123.45 |
| 340 | // f := SafeFloatValue("invalid") // 0.0 |
| 341 | func SafeFloatValue(value interface{}) float64 { |
| 342 | switch v := value.(type) { |
| 343 | case float64: |
| 344 | if isFiniteFloat(v) { |
| 345 | return v |
| 346 | } |
| 347 | case int: |
| 348 | return float64(v) |
| 349 | case int64: |
| 350 | return float64(v) |
| 351 | case string: |
| 352 | if f, err := strconv.ParseFloat(v, 64); err == nil && isFiniteFloat(f) { |
| 353 | return f |
| 354 | } |
| 355 | } |
| 356 | |
| 357 | return 0.0 |
| 358 | } |
| 359 | |
| 360 | func isFiniteFloat(value float64) bool { |
| 361 | return !math.IsNaN(value) && !math.IsInf(value, 0) |