Slider组件,step设置为0.1时,滑动时显示的value不是正常的35.1、35.2、35.3,而是35.70000076293945、36.400001525878906这类数值,如何解决?
问题代码示例参考如下:
@Entry @Component struct Question { textTimerController: TextTimerController = new TextTimerController(); @State tempLatrue: number = 35; build() { Column() { Slider({ value: this.tempLatrue, min: 34.5, max: 43.1, style: SliderStyle.OutSet, step: 0.1 }) .width('100%') .margin({ top: 15, bottom: 15 }) .onChange((value: number) => { this.tempLatrue = value; }).showTips(true, `${this.tempLatrue}`) } } }
问题效果预览:

浮点数在计算机中是通过二进制形式存储的,某些十进制浮点数在二进制中无法精确表示,导致了运算结果的精度问题。
@Entry @Component struct TextTimerExample { textTimerController: TextTimerController = new TextTimerController(); @State tempLatrue: number = 35; build() { Column() { Slider({ value: this.tempLatrue, min: 34.5, max: 43.1, style: SliderStyle.OutSet, step: 0.1 }) .width('100%') .margin({ top: 15, bottom: 15 }) .onChange((value: number) => { this.tempLatrue = Number.parseFloat(value.toFixed(3).slice(0, -1)); }).showTips(true, `${this.tempLatrue}`) } } }