对数组中对象的字段四舍五入

import (
    "encoding/json"
    "log"
    "strconv"
)

func main() {
    m := []map[string]interface{}{
        {"a": 1.25554545, "b": 0, "c": 3},
        {"a": 2, "b": 0, "c": 3},
        {"a": 1, "b": 1, "c": 3},
        {"a": 3, "b": 0, "c": 3},
        {"a": 5, "b": 2, "c": 3},
    }
    log.Println(GetDecimal2(m))
}

func GetDecimal2(obj interface{}) interface{} {
    data, _ := json.Marshal(obj)
    ms := []map[string]interface{}{}
    json.Unmarshal(data, &ms)
    for i, m := range ms {
        for k, v := range m {
            if vf, ok := v.(float64); ok && vf != 0 {
                ms[i][k], _ = strconv.ParseFloat(strconv.FormatFloat(vf, 'f', 2, 64), 64)
            }
        }
    }
    return ms
}

你可能感兴趣的:(对数组中对象的字段四舍五入)