How to convert NSString to float without rounding it? - swift

I have tried the following but when I convert the string it is automatically rounded.
let str = "10,60"
let str2 = (str as NSString).floatValue //prints "10.0"
//What I would like to do
let str2 = (str as NSSTring).floatValueNotRounded //prints "10,60"

.floatValue does not handle local formats and your number uses a comma as the decimal point - the the parse just stops at the comma and you get 10. Use either NumberFormatter or Scanner to parse localised numbers. E.g.:
let formatter = NumberFormatter()
let val = formatter.number(from: str)
should work provided your locale uses the comma as the decimal point. If you are in one locale and wish to parse numbers written according to another you can set locale property of the formatter.

Related

String number with limited precision fraction digits in Swift

What would be the fastest way to convert a String number "1234.5678" to an NSNumber with precision -> 1234.56 and back to String "1234.56".
let numberFormatter = NumberFormatter()
numberFormatter.maximumFractionDigits = 2
numberFormatter.string(from: numberFormatter.number(from: "1234.534234")!)
This code does not look that beautiful. Any ideas?
You can use the new formatted method and specify the number of precision fraction length to two:
let decimal = Decimal(
sign: .plus,
exponent: -4,
significand: 12345678
) // 1234.5678
decimal.formatted(.number.precision(.fractionLength(2))) // "1,234.57"
decimal.formatted(.number.grouping(.never).precision(.fractionLength(2))) // "1234.57"
decimal.formatted(.number.grouping(.never).rounded(rule: .towardZero).precision(.fractionLength(2))) // "1234.56"
Alternatively if you are only interested in the string regardless of any numeric modification like rounding you can strip the unwanted characters with Regular Expression
let string = "1234.5678"
let trimmedString = string.replacingOccurrences(of: "(\\d+\\.\\d{2})\\d.",
with: "$1",
options: .regularExpression)

How to convert characters of an Integer β€œ1” to a string β€œOne” into in swift

I want converting int number in to letter of this number .I Have one text field .in this text field user can write number then i want convertin this number to letter . for example i want convert 11 to eleven .how can i do this work in swift .
You can use like this :
let formatter = NumberFormatter()
formatter.numberStyle = .spellOut
let english = formatter.string(from: 1)
and you can Refer this Awesome Answer for objective-c.
If you wanted to get that in Espanol , you would set a locale like this:
formatter.locale = Locale(identifier: "es_ES")
let spanish = formatter.string(from:1)

How to convert Exponential Value to Decimal Value

let balance = "2.477854178281608e-06"
// I have to convert this exponential value in Decimal
/* Already tried the below-mentioned solution, but not working */
let numberFormatter = NumberFormatter()
numberFormatter.numberStyle = .decimal
let finalNumber = numberFormatter.number(from: balance)
print(finalNumber!)
Value is printing "2.477854178281608e-06\n"
Any help will be appreciated.
let balance = "2.477854178281608e-06"
// I have to convert this exponential value in Decimal
This is not an exponential value. This is a string that represents a number using exponential format. You seem to want a string representing the same number in a different format. The important thing here is that neither string is "the value." The value is the same regardless of representation (or approximately the same if the representation is limited).
So first you need the value represented by the string. To do that, convert it to a Double.
let value = Double(balance)!
Now, you say you want to convert that to a string in decimal format (I assume you mean 0.000...). So you need a formatter:
let numberFormatter = NumberFormatter()
numberFormatter.numberStyle = .decimal
numberFormatter.maximumFractionDigits = 20
let string = numberFormatter.string(for: value)!
print(string) // 0.00000247785417828161
You'll note that this value is slightly different than the previous value. That's because there are rounding errors when dealing with values this small.
If all of these base-10 digits are important, you can work with the Decimal type rather than Double. This avoids decimal/binary rounding, but is less convenient and slower for some kinds of math. If this is a type of currency that is expressed in base-10 units (which is basically all of them), you always want to work with Decimal and never with Double.
let balance = "2.477854178281608e-06"
let value = Decimal(string: balance)!
let numberFormatter = NumberFormatter()
numberFormatter.numberStyle = .decimal
numberFormatter.maximumFractionDigits = 21
let string = numberFormatter.string(for: value)!
print(string) // 0.000002477854178281608

Int won't show numbers after the comma

I want to get from a string to a int. My problem is now that i'll get a int value but it wont show the number after the comma. If the string is -0,23, than the int will print 0.How can i fix this? Please help.
let int = (percent_change_24hArray[indexPath.row] as NSString).integerValue
You will probably have to use a NumberFormatter for that, set up for your locale. In the US, the decimal separator is a period. (".") A comma is considered a delimiter.
Plus, assuming you are in a locale where the decimal separator is a comma, converting to an integer will truncate the part after the decimal separator anyway.
Code like the code below should work:
var str = "-0,23"
let formatter = NumberFormatter()
formatter.numberStyle = .decimal
formatter.locale = Locale(identifier: "fr_FR")
let aVal = formatter.number(from: str)?.doubleValue
(I'm using France's French as the locale since France uses a comma as a decimal separator.)
Note that you need to think carefully about where you numeric strings come from in order to decide how to handle locale. if these are user-entered strings then you should probably use a number formatter with the default locale for the device. That way a European user can use a comma as a decimal separator and a US user can use a period as a decimal separator and both will work.
You need to use a float, integers don't take numbers after the comma
https://developer.apple.com/documentation/swift/float

Convert NumberFormatter.Style.spellOut to Int

Try to find a way to convert plain English number (e.g., One, Two...) to Int (e.g., 1, 2...)
I know that there is way to convert from Int to English using
numberFormatter:NumberFormatter = NumberFormatter()
numberFormatter.numberStyle = NumberFormatter.Style.spellOut
var string = numberFormatter.string(from: 3) // "three"
Is there any reverse way of converting this?
I am trying to avoid using array of String like ["One", "Two"..]
Number formatters work in both directions, so you can just use:
let num = numberFormatter.number(from: string)
But you'll need to take some care to make sure it exactly matches the output of the forward direction. "three" will translate to 3, but "Three" won't.
As Sulthan notes, this is absolutely sensitive to the locale of the formatter (which you can set to be different than the user's locale if that's necessary). It is strongly assuming that the input and output from the same formatter match.