bod*_*ser 2 casting go floating-point-precision
我想检查一个 float32 是否有两个小数位。我这样做的 javascript 方法如下所示:
step := 0.01
value := 9.99
if int(value/step) % 1 == 0 {
printf("has two decimal places!")
}
Run Code Online (Sandbox Code Playgroud)
上面的例子也有效。但是,当 step 不正确时它将不起作用,因为 go 然后无法正确地从 float64 转换为 int。
例子:
step := 0.1
value := 9.99
if int(value/step) % 1 == 0 {
printf("has two decimal places!")
}
Run Code Online (Sandbox Code Playgroud)
编译器错误: constant 9.99 truncated to integer
当我们使用动态值时,它只会为每种情况返回 true。
那么计算小数位数的合适方法是什么?
你必须欺骗它,添加一个额外的变量:
step := 0.1
value := 9.99
steps := value / step
if int(steps)%1 == 0 {
fmt.Println("has two decimal places!")
}
Run Code Online (Sandbox Code Playgroud)
或者在将其转换为 int 之前投射您的步骤,例如:
int(float64(value / step))
Run Code Online (Sandbox Code Playgroud)
//编辑
hacky 非数学方法是将其转换为字符串并将其拆分,例如:
func NumDecPlaces(v float64) int {
s := strconv.FormatFloat(v, 'f', -1, 64)
i := strings.IndexByte(s, '.')
if i > -1 {
return len(s) - i - 1
}
return 0
}
Run Code Online (Sandbox Code Playgroud)
//更新了一个小的优化
| 归档时间: |
|
| 查看次数: |
5092 次 |
| 最近记录: |