Elvis Shi
December 15, 2021
620

Decimal、正しく使ってる？ / Are you using Decimal correctly?

Elvis Shi

December 15, 2021

Transcript

2. } var employedBy = "YUMEMI Inc." var job = "iOS

Tech Lead" var favoriteLanguage = "Swift" var twitter = "@lovee" var qiita = "lovee" var github = "el-hoshino" var additionalInfo = """ M1 Max MacBook Proࠓ೔ಧ͍ͨʂ """ final class Me: Developable, Talkable {

5. // ࠓ݄ͷڅ༩ var myYumeCoin = 0.2 // ࠓ݄ͷϘʔφε myYumeCoin +=

0.1 // ϘʔφεΛ࢖ͬͯങ͍෺ʂ myYumeCoin -= 0.1 // ࢒ߴ֬ೝ print(myYumeCoin) // 0.20000000000000004 ??????

9. // ࠓ݄ͷڅ༩ var myYumeCoin = 0.2 // ࠓ݄ͷϘʔφε myYumeCoin +=

0.1 // ϘʔφεΛ࢖ͬͯങ͍෺ʂ myYumeCoin -= 0.1 // ࢒ߴ֬ೝ print(myYumeCoin) // 0.20000000000000004 ??????
10. import Foundation // ࠓ݄ͷڅ༩ var myYumeCoin: Decimal = 0.2 //

ࠓ݄ͷϘʔφε myYumeCoin += 0.1 // ϘʔφεΛ࢖ͬͯങ͍෺ʂ myYumeCoin -= 0.1 // ࢒ߴ֬ೝ print(myYumeCoin) // 0.2 🎉 'PVOEBUJPO͕ඞཁ ܕΛ໌ࣔతʹ%FDJNBMʹࢦఆ

13. import Foundation // ࠓ݄ͷڅ༩ var myYumeCoin: Decimal = 0.2 //

ࠓ݄ͷϘʔφε myYumeCoin += 0.1 // ϘʔφεΛ࢖ͬͯങ͍෺ʂ myYumeCoin -= 0.1 // ࢒ߴ֬ೝ print(myYumeCoin) // 0.2 🎉
14. import Foundation // ࠓ݄ͷڅ༩ var myYumeCoin: Decimal = 0.2 //

ࠓ݄ͷϘʔφε myYumeCoin += 0.1 // ϘʔφεΛ࢖ͬͯങ͍෺ʂ myYumeCoin -= 0.1 // Decimal Λ࢖ͬͯਖ਼֬ͳڅ༩ܭࢉ͕Ͱ͖͔ͨΒ͍͑΍Ϙʔφεʂ myYumeCoin += 123.456 // ࢒ߴ֬ೝ print(myYumeCoin) // 123.65599999999997952 !!!?????

16. DecimalͷϦςϥϧ୅ೖ w খ਺ϦςϥϧͰDecimalΛ୅ೖͰ͖Δͷ͸ɺ ExpressibleByFloatLiteralΛར༻ͨ݁͠Ռ w ࣮૷͸init(floatLiteral value: Double) w DecimalΛ࡞Δલʹͦ΋ͦ΋ઌʹҰճDoubleΛ

࡞ͬͯͦͷ݁ՌΛ୅ೖ͍ͯ͠Δ͚ͩʂ

18. %FDJNBMΛखܰʢʁʣʹѻ͏ͨΊͷ   ΠχγϟϥΠβʔ • init(_ value: String, format: Decimal.FormatStyle, lenient:

Bool = true) throws // iOS 15+ • init?(string: String, locale: Locale? = nil) // iOS 7+ • // etc…
19. import Foundation // ࠓ݄ͷڅ༩ var myYumeCoin: Decimal = 0.2 //

ࠓ݄ͷϘʔφε myYumeCoin += 0.1 // ϘʔφεΛ࢖ͬͯങ͍෺ʂ myYumeCoin -= 0.1 // Decimal Λ࢖ͬͯਖ਼֬ͳڅ༩ܭࢉ͕Ͱ͖͔ͨΒ͍͑΍Ϙʔφεʂ myYumeCoin += 123.456 // ࢒ߴ֬ೝ print(myYumeCoin) // 123.65599999999997952 !!!?????
20. import Foundation // … // Decimal Λ࢖ͬͯਖ਼֬ͳڅ༩ܭࢉ͕Ͱ͖͔ͨΒ͍͑΍Ϙʔφεʂ //myYumeCoin += 123.456

// ࠓ౓ͦ͜ʂ myYumeCoin += try! .init("123.456", format: .number) // ࢒ߴ֬ೝ print(myYumeCoin) // 123.656 🎉