Search code examples
iosswiftuikit

How to precisely round percentage value to 2 decimal place double?


Scenario: I have a UISlider that allows for values from 0 to 100. This slider will return a float such as 76.2345654234. In core data, I want to store this percentage as a double in this format: 0.76.

Problem: Using floor() or round() on the float gives me 76. Good. But if I divide by 100 now pesky trailing decimals show up. Sometimes certain numbers will work and give me 2 decimal places, but without fault, every time, another number won't and I'll end up with something that looks like this: 0.760000001.

No solution I've seen on this website or otherwise works 100% of the time. Surely there must be a way do to something this simple? Thanks!!


Solution

  • I want to store this percentage

    Great. Store a percentage. That's an integer in your case, 76. Store that.

    For all the gory details, see The Floating-Point Guide, but for your purposes, the answer is to store the value as an integer.

    If you really want a decimal value, then you can set your type in Core Data to Decimal, and you'll get exactly what you want here, but I recommend using integers for two-significant-digit percentages. It's much more straight-forward.