How can we truncate float64 type to a particular precision?

前端 未结 12 1423
礼貌的吻别
礼貌的吻别 2021-02-02 05:33
package main

import (
    \"fmt\"
    \"strconv\"
    )

func main() {
    k := 10/3.0
    i := fmt.Sprintf(\"%.2f\", k)
    f,_ := strconv.ParseFloat(i, 2)
    fmt.Pri         


        
12条回答
  •  一向
    一向 (楼主)
    2021-02-02 06:05

    The simplest solution is numeric truncation (assuming i is a float and you want a precision of 2 decimal points):

    float64(int(i * 100)) / 100
    

    For example:

    i := 123456.789
    x := float64(int(i * 100)) / 100
    // x = 123456.78
    

    BEWARE!

    If you're dealing with large numbers (numbers that can cross the max value boundaries), you should know that the above can lead to serious floating point accuracy issues:

    i := float64(1<<63) // 9223372036854775808.0
    fmt.Println(i, float64(int64(i * 10)) / 10)
    

    Prints: 9.223372036854776e+18 -9.223372036854776e+17

    See also:

    1. how 32 bit floating point numbers work
    2. how 64 bit floating point numbers work
    3. golang math numeric value range constants
    4. golang math/big

提交回复
热议问题