renldx
renldx

Reputation: 13

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!!

Upvotes: 0

Views: 1171

Answers (2)

John Lindgren
John Lindgren

Reputation: 867

You said you want to store a number:

as a double

and

in this format: 0.76

You can't do both, you have to pick one. A Double is not a decimal, and it can't store most decimal numbers exactly. See this question:

Why can't decimal numbers be represented exactly in binary?

If you need to store decimal numbers exactly, use a different type than a Double: for example, the Decimal type). If for some reason you have to store your number as a Double, then you'll have to live with not storing decimal numbers exactly.

Side note: There are ways to round inexact Double values back to nearby decimals when you print them, but that's a different topic and not the question you asked.

Upvotes: 1

Rob Napier
Rob Napier

Reputation: 299485

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.

Upvotes: 0

Related Questions