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)
CodePudding user response:
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.
CodePudding user response:
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.