如何计算给定小数位数的浮点数?

时间:2020-09-12 17:49:39

标签: go

我需要一种算法来计算给定整数和小数点后的浮点数。

这里有几个例子可以理解我的意思:

  • Amount = 484,DecimalPlaces = 0应该返回“ 484”
  • Amount = 484,DecimalPlaces = 1应该返回“ 48.4”
  • Amount = 484,DecimalPlaces = 2应该返回“ 4.84”
  • Amount = 484,DecimalPlaces = 3应该返回“ 0.484”
  • Amount = 484,DecimalPlaces = 4应该返回“ 0.0484”
  • Amount = 484,DecimalPlaces = 5应该返回“ 0.00484”
  • ...

我已经有一个算法,但是我不知道如何求解前导零。

这是我的方法(我正在使用golang btw):

func GetAmount(amount, places int) string {
    runes := []rune(strconv.Itoa(amount))
    result := ""
    for j := len(runes) - 1; j >= 0; j-- {
        result = string(runes[j]) + result
        if j == len(runes)-places {
            result = "." + result
        }
    }   
    return result
}

谢谢!

1 个答案:

答案 0 :(得分:4)

可能不是最有效的方法,但这是一个单行代码:

func GetAmount(amount, places int) string {
    return fmt.Sprintf("%.*f", places, float64(amount)/math.Pow10(places))
}

https://play.golang.org/p/ppipUqX9eSF

编辑:对@perreal进行单线建议!