0

I'm trying to convert a number which is a string ("1.51") into a decimal so I can store it inside Core Data. But when I pull that decimal number back out, it's 1.50999...

Here's the code I use to convert from the string and then store.

priceFloat = (row[13] as NSString).floatValue
            
            newItem.royalty =  NSDecimalNumber(value: priceFloat)

And I display it in SwiftUI, like this...

 Text("\(sale.royalty ?? NSDecimalNumber(0))")
                            .frame(maxWidth: .infinity, alignment: .trailing)
Author
  • 15
  • 2

2 Answers2

4

When you turned it into a Float by calling .floatValue, you've already applied binary rounding. Use the Decimal(string:locale:) init to convert it directly from a string to a Decimal.

Rob Napier
  • 286,113
  • 34
  • 456
  • 610
  • Had to do "newItem.royalty = Decimal(string:row[13]) as NSDecimalNumber?" But apart from that it worked, perfectly, thanks. – Author Dec 12 '22 at 15:59
0

SwiftUI does the formatting for us and updates the labels or text fields automatically if the locale changes, it's simply Text(sale.royalty, format: .number) and there are many other options.

malhal
  • 26,330
  • 7
  • 115
  • 133