我正在try 为我的应用程序重新创建一个计算器.它看起来像是在重建一辆自行车,但这是我的第一个项目,我没想到会有这么多挑战.最后一个是浮点误差.我知道这是一个常见的问题,但我不知道如何用计算器来解决它.

显然,计算器可以很好地工作.我试着寻找一些原型,他们中的大多数都有相同的问题或比这一个更多.

为了在屏幕上显示结果,我使用了DOUBLE插值法,它给出了一个结果,例如将0.1%加到0.2%等于0.2999999.或将0.3乘以3等于0.8999999999.

四舍五入是不合适的,因为我们永远不知道小数点后有多少位有用的数字.

如何将此计算表示给用户,类似于本机计算器,例如: 我需要0.1+0.2=0.3同时1/3=0.33333333

下面是计算示例和我对字符串的插补,以显示结果:

struct air: View {
    
    @State var data: String = "0" // creating var for showing
    @State var firstNumber: Double = 0.3 // exact number which I have problem could be 0.3, 0.6
    @State var secondNumber: Double = 3 // could be 3, 9, 12
    @State var result: Double = 0 // result of calculation
    
    
    var body: some View {
        VStack{
            Button("Push"){ // Initiating calculation
                result = calculate(first: firstNumber, second: secondNumber)
                data = String(result)
            }.frame(width: 80, height: 40)
                .background(Color.gray)
                .foregroundColor(.white)
            Text("result: Double = \(result)") // can see that result as Double is correct
                .font(.title)
            Text("data: String = \(data)") // can see that result as interpolated to String is incorrect and shows number with 9 in period
                .font(.title)
        }
    }
}
func calculate(first: Double, second:Double) -> Double {
    return first * second
}

推荐答案

因为您想要以十进制运算,所以使用Decimal类型而不是Double(它以二进制运算,因此以二进制四舍五入).

将所有引用从Double更改为Decimal后,您可能还需要在某些地方使用.formatted()来创建字符串.DECIMAL有少量缺失的API挂钩.例如:

data = result.formatted()

如果您想要不同的格式,可以将各种选项传递给.formatted.例如:

data = result.formatted(.number.precision(.fractionLength(2))))

另请参阅,Is floating point math broken?

Ios相关问答推荐

React Native Text组件内部TextInput组件在iOS上的问题:在TextInput组件内部键入文本时失go 焦点

第三方框架的iOS隐私声明

缺少预期的键:';NSPrival yCollectedDataTypes';

如何在SwiftUI ScrollView中zoom 中心项目?

Flutter iOS 键盘问题:. TextInputType.number 中缺少字符

将 Riverpod 从 StateNotifier 修复为 NotifierProvider 以及应用程序生命周期监控

错误地提取问题的答案选项

iOS - 判断开发者模式是否开启 (Swift)

如何在 SwiftUI 中将选项卡放在滚动视图中?

iOS 16 堆栈视图中按钮的奇怪动画

iOS 如何使用 Alamofire 解析 JSON 可编码数组

迁移到 UIKit 生命周期的应用程序不会调用 SceneDelegate

AVPlayer 退出全屏

无法结合 UIImageView 旋转动画和 tableView 部分重新加载

Apple Push Service 证书不受信任

动画 UILabel 字体大小更改

SwiftUI NavigationView navigationBarTitle LayoutConstraints 问题

判断密钥是否存在于 NSDictionary 中

我可以通过 UIAppearance 代理设置哪些属性?

Swift:如何在设备旋转后刷新 UICollectionView 布局