UPGRADE YOUR SKILLS: Learn advanced Swift and SwiftUI on Hacking with Swift+! >>

SOLVED: Measurement conversion error?

Forums > Swift

I've been playing with "Measurements" and noticed there's a little mismatch when converting a measurement:

import Foundation

var someMeasurement: Measurement<UnitMass> = Measurement(value: 0.5, unit: .milligrams)

print(someMeasurement.converted(to: .micrograms))

500 μg

499.99999999999994 µg

Am I doing something wrong?


This is more likely a limitation computers have when representing floating-point values and doing floating-point math than an error in your code. A value you expect to be something like .5 ends up with a value like .4999999999999, and the printed value is slightly off.


TAKE YOUR SKILLS TO THE NEXT LEVEL If you like Hacking with Swift, you'll love Hacking with Swift+ – it's my premium service where you can learn advanced Swift and SwiftUI, functional programming, algorithms, and more. Plus it comes with stacks of benefits, including monthly live streams, downloadable projects, a 20% discount on all books, and free gifts!

Find out more

Sponsor Hacking with Swift and reach the world's largest Swift community!

Reply to this topic…

You need to create an account or log in to reply.

All interactions here are governed by our code of conduct.

Unknown user

You are not logged in

Log in or create account

Link copied to your pasteboard.