Convert NSString to currency format - ios

In Java we do this statement to have a $ currency format.
double num1 = 3.99 ;
double num2 = 1.00 ;
double total = num1 + num2;
System.out.printf ("Total: $ %.2f", total);
The result is:
Total: $4.99
//--------------------------------
Now in iOS how can I get same format if I have the following statement :
total.text = [NSString stringWithFormat:#"$ %d",([self.coursePriceLabel.text intValue])+([self.courseEPPLabel.text intValue])+10];
Note:
If I use doubleValue the output always is 0 .

You can do the same thing with NSString:
NSString *someString = [NSString stringWithFormat:#"$%.2lf", total];
Note that the format specifier is "%lf" rather than just "%f".
But that only works for US dollars. If you want to make your code more localizable, the right thing to do is to use a number formatter:
NSNumber *someNumber = [NSNumber numberWithDouble:total];
NSNumberFormatter *nf = [[NSNumberFormatter alloc] init];
[nf setNumberStyle:NSNumberFormatterCurrencyStyle];
NSString *someString = [nf stringFromNumber:someNumber];
Of course, it won't do to display a value calculated in US dollars with a Euro symbol or something like that, so you'll either want to do all your calculations in the user's currency, or else convert to the user's currency before displaying. You may find NSValueTransformer helpful for that.

Related

convert NSString to long value [duplicate]

How can I convert a NSString containing a number of any primitive data type (e.g. int, float, char, unsigned int, etc.)? The problem is, I don't know which number type the string will contain at runtime.
I have an idea how to do it, but I'm not sure if this works with any type, also unsigned and floating point values:
long long scannedNumber;
NSScanner *scanner = [NSScanner scannerWithString:aString];
[scanner scanLongLong:&scannedNumber];
NSNumber *number = [NSNumber numberWithLongLong: scannedNumber];
Thanks for the help.
Use an NSNumberFormatter:
NSNumberFormatter *f = [[NSNumberFormatter alloc] init];
f.numberStyle = NSNumberFormatterDecimalStyle;
NSNumber *myNumber = [f numberFromString:#"42"];
If the string is not a valid number, then myNumber will be nil. If it is a valid number, then you now have all of the NSNumber goodness to figure out what kind of number it actually is.
You can use -[NSString integerValue], -[NSString floatValue], etc. However, the correct (locale-sensitive, etc.) way to do this is to use -[NSNumberFormatter numberFromString:] which will give you an NSNumber converted from the appropriate locale and given the settings of the NSNumberFormatter (including whether it will allow floating point values).
Objective-C
(Note: this method doesn't play nice with difference locales, but is slightly faster than a NSNumberFormatter)
NSNumber *num1 = #([#"42" intValue]);
NSNumber *num2 = #([#"42.42" floatValue]);
Swift
Simple but dirty way
// Swift 1.2
if let intValue = "42".toInt() {
let number1 = NSNumber(integer:intValue)
}
// Swift 2.0
let number2 = Int("42')
// Swift 3.0
NSDecimalNumber(string: "42.42")
// Using NSNumber
let number3 = NSNumber(float:("42.42" as NSString).floatValue)
The extension-way
This is better, really, because it'll play nicely with locales and decimals.
extension String {
var numberValue:NSNumber? {
let formatter = NumberFormatter()
formatter.numberStyle = .decimal
return formatter.number(from: self)
}
}
Now you can simply do:
let someFloat = "42.42".numberValue
let someInt = "42".numberValue
For strings starting with integers, e.g., #"123", #"456 ft", #"7.89", etc., use -[NSString integerValue].
So, #([#"12.8 lbs" integerValue]) is like doing [NSNumber numberWithInteger:12].
You can also do this:
NSNumber *number = #([dictionary[#"id"] intValue]]);
Have fun!
If you know that you receive integers, you could use:
NSString* val = #"12";
[NSNumber numberWithInt:[val intValue]];
Here's a working sample of NSNumberFormatter reading localized number NSString (xCode 3.2.4, osX 10.6), to save others the hours I've just spent messing around. Beware: while it can handle trailing blanks ("8,765.4 " works), this cannot handle leading white space and this cannot handle stray text characters. (Bad input strings: " 8" and "8q" and "8 q".)
NSString *tempStr = #"8,765.4";
// localization allows other thousands separators, also.
NSNumberFormatter * myNumFormatter = [[NSNumberFormatter alloc] init];
[myNumFormatter setLocale:[NSLocale currentLocale]]; // happen by default?
[myNumFormatter setFormatterBehavior:NSNumberFormatterBehavior10_4];
// next line is very important!
[myNumFormatter setNumberStyle:NSNumberFormatterDecimalStyle]; // crucial
NSNumber *tempNum = [myNumFormatter numberFromString:tempStr];
NSLog(#"string '%#' gives NSNumber '%#' with intValue '%i'",
tempStr, tempNum, [tempNum intValue]);
[myNumFormatter release]; // good citizen
I wanted to convert a string to a double. This above answer didn't quite work for me. But this did: How to do string conversions in Objective-C?
All I pretty much did was:
double myDouble = [myString doubleValue];
Thanks All! I am combined feedback and finally manage to convert from text input ( string ) to Integer. Plus it could tell me whether the input is integer :)
NSNumberFormatter * f = [[NSNumberFormatter alloc] init];
[f setNumberStyle:NSNumberFormatterDecimalStyle];
NSNumber * myNumber = [f numberFromString:thresholdInput.text];
int minThreshold = [myNumber intValue];
NSLog(#"Setting for minThreshold %i", minThreshold);
if ((int)minThreshold < 1 )
{
NSLog(#"Not a number");
}
else
{
NSLog(#"Setting for integer minThreshold %i", minThreshold);
}
[f release];
I think NSDecimalNumber will do it:
Example:
NSNumber *theNumber = [NSDecimalNumber decimalNumberWithString:[stringVariable text]]];
NSDecimalNumber is a subclass of NSNumber, so implicit casting allowed.
What about C's standard atoi?
int num = atoi([scannedNumber cStringUsingEncoding:NSUTF8StringEncoding]);
Do you think there are any caveats?
You can just use [string intValue] or [string floatValue] or [string doubleValue] etc
You can also use NSNumberFormatter class:
you can also do like this code 8.3.3 ios 10.3 support
[NSNumber numberWithInt:[#"put your string here" intValue]]
NSDecimalNumber *myNumber = [NSDecimalNumber decimalNumberWithString:#"123.45"];
NSLog(#"My Number : %#",myNumber);
Try this
NSNumber *yourNumber = [NSNumber numberWithLongLong:[yourString longLongValue]];
Note - I have used longLongValue as per my requirement. You can also use integerValue, longValue, or any other format depending upon your requirement.
Worked in Swift 3
NSDecimalNumber(string: "Your string")
I know this is very late but below code is working for me.
Try this code
NSNumber *number = #([dictionary[#"keyValue"] intValue]]);
This may help you. Thanks
extension String {
var numberValue:NSNumber? {
let formatter = NumberFormatter()
formatter.numberStyle = .decimal
return formatter.number(from: self)
}
}
let someFloat = "12.34".numberValue

Objective C, Trim a float

I have float like 3500,435232123. All I want to know if exists (in Objective C) a function that let me keep just the last 4 digits in my case is 2123.
You can use NSNumberFormatter
NSNumberFormatter *format = [[NSNumberFormatter alloc]init];
[format setNumberStyle:NSNumberFormatterDecimalStyle];
[format setRoundingMode:NSNumberFormatterRoundHalfUp];
[format setMaximumFractionDigits:4];
[format setMinimumFractionDigits:4];
string = [NSString stringWithFormat:#"%#",[format stringFromNumber:[NSNumber numberWithFloat:65.50055]] ;
Or simply
NSString *string = [NSString stringWithFormat:#"%.04f", floatValue];
If you want only last four digits, convert the float to a string
NSString *string = [NSString stringWithFormat:#"%f", floatValue];
and get the last four characters
NSString *lastFour = [string substringFromIndex: [string length] - 4];
It you want to get the decimal part, you can do x - floor(x). For instance:
float x = 3500,435232123;
NSString *string = [NSString stringWithFormat:#"%.04f", x - floor(x)];
And to get 4 decimal digits do what Fawad Masud says.
No there is no such function, as far as i know. But here is a way to achieve exactly what you want.
First you have to round it to four digits after point:
NSString *exampleString = [NSString stringWithFormat:#"%.04f", valueToRound];
Then you get the location for the comma inside the exampleString:
NSRange commaRange = [valueString rangeOfString:#","];
Finally you create the finalString with the values from that NSRange. The substring starts at commaRange.location+commaRange.lengthbecause thats the index directly after the comma.
NSString *finalString = [valueString substringWithRange:NSMakeRange(commaRange.location+commaRange.length,valueString.length-commaRange.location-commaRange.length)];
Hope that helps you.
I think is no predefined function for that.
and the solution i thought of is:
float floatNum = 3500.435232123;
converting float number to string and trim/substring the string, like for example:
NSString *stringFloat = [NSString stringWithFormat:#"%f", floatNum];
NSString *newString = [stringFloat substringWithRange:NSMakeRange(stringFloat.length - 4, stringFloat.length)];
NSLog(#"%#", newString);
another is something like:
NSString *stringFloat = [NSString stringWithFormat:#"%f", floatNum];
//separates the floating number to
arr[0] = whole number
arr[1] = decimals
NSArray *arr=[str componentsSeparatedByString:#"."];
since you just want to work on the decimal, i think arr[1] is what you need..
NSString *stringDecimals = (NSString *)arr[1];
if ( stringDecimals.length > 4) //check the length of the decimals then cut if exceeds 4 character..
{
stringDecimals = [stringDecimals substringWithRange:NSMakeRange(stringDecimals.length - 4, stringDecimals.length)];
}
NSLog(#"stringDecimals: %#", stringDecimals);

Convert unsigned long to float with 2 precision decimal value

I am trying to convert the value to float with 2 precision decimal format.
NSString* formattedNumber = [NSString stringWithFormat:#"%.2lu", (unsigned long)users.count];
float totalRatingCount = atof([formattedNumber UTF8String]);
This gives me values such as
1.000000
2.000000
3.000000
What I want is the following
1.00
2.00
3.00
Where am i going wrong?
A float has no precision value, it's not a fixed point value. However, there is an easier way to convert to float:
CGFloat totalRating = [formattedNumber floatValue];
to print a float with 2dp's of precision, use the format string #"%.02f"
You need to use %.2f format specifier as
NSString* formattedNumber = [NSString stringWithFormat:#"%.2f", (float)users.count];
float totalRatingCount = atof([formattedNumber UTF8String]);
and you'll get the desired out put with 2 values precision after decimal.
Using NSNumberFormatter, you can rounding number up to two digit.
double d = 12.1278;
NSNumberFormatter *formatter = [NSNumberFormatter new];
[formatter setRoundingMode:NSNumberFormatterRoundFloor];
[formatter setMinimumFractionDigits:2];
[formatter setMaximumFractionDigits:2];
NSString *numberString = [formatter stringFromNumber:#(d)];
NSLog(#"numberString: %#", numberString);
Output is :
numberString: 12.12
Try this:
NSNumber *number = [NSNumber numberWithFloat:(unsigned long)users.count];
NSNumberFormatter* nf=[[NSNumberFormatter alloc]init];
nf.minimumFractionDigits=2;
nf.maximumFractionDigits=2;
NSString* str = [nf stringFromNumber:number];
NSLog(#"%#",str);

Is there any easy way to round a float with one digit number in objective c?

Yes. You are right. Of Course this is a duplicate question. Before flag my question, please continue reading below.
I want to round a float value, which is
56.6748939 to 56.7
56.45678 to 56.5
56.234589 to 56.2
Actually it can be any number of decimal precisions. But I want to round it to nearest value. (If it is greater than or equal to 5, then round up and if not, then round down).
I can do that with the below code.
float value = 56.68899
NSNumberFormatter *numberFormatter = [[NSNumberFormatter alloc]init];
[numberFormatter setMaximumFractionDigits:1];
[numberFormatter setRoundingMode:NSNumberFormatterRoundUp];
NSString *roundedString = [numberFormatter stringFromNumber:[NSNumber numberWithFloat:value]];
NSNumber *roundedNumber = [NSNumber numberFromString:roundedString];
float roundedValue = [roundedNumber floatValue];
Above code looks like a long process. I have several numbers to round off. So this process is hard to convert a float value into NSNumber and to NSString and to NSNumber and to float.
Is there any other easy way to achieve what I asked ?
I still have a doubt in the above code. It says roundUp. So when it comes to roundDown, will it work?
Can't you simply multiply by 10, round the number, then divide by 10?
Try
CGFloat float1 = 56.6748939f;
CGFloat float2 = 56.45678f;
NSLog(#"%.1f %.1f",float1,float2);
56.7 56.5
EDIT :
float value = 56.6748939f;
NSString *floatString = [NSString stringWithFormat:#"%.1f",floatValue];
float roundedValue = [floatString floatValue];
NSString* strr=[NSString stringWithFormat: #"%.1f", 3.666666];
NSLog(#"output is: %#",strr);
output is:3.7
float fCost = [strr floatValue];
This works for me
NSNumberFormatter* formatter = [[NSNumberFormatter alloc] init];
[formatter setMaximumFractionDigits:1];
[formatter setMinimumFractionDigits:0];
CGFloat firstnumber = 56.6748939;
NSString *result1 = [formatter stringFromNumber:[NSNumber numberWithFloat:firstnumber]];
NSLog(#"RESULT #1: %#",result1);
CGFloat secondnumber = 56.45678;
NSString *result2 = [formatter stringFromNumber:[NSNumber numberWithFloat:secondnumber]];
NSLog(#"RESULT #2: %#",result2);
CGFloat thirdnumber = 56.234589;
NSString *result3 = [formatter stringFromNumber:[NSNumber numberWithFloat:thirdnumber]];
NSLog(#"RESULT #2: %#",result3);
You don't want float, because that only gives you six or seven digits precision. You also don't want CGFloat, because that only gives you six or seven digits precision except on an iPad Air or iPhone 5s. You want to use double.
Rounding to one digit is done very simply:
double x = 56.6748939;
double rounded = round (10 * x) / 10;
You can use
[dictionaryTemp setObject:[NSString stringWithFormat:#"%.1f",averageRatingOfAllOrders] forKey:#"AvgRating"];
%.1f will give us value 2.1 only one digit after decimal point.
Try this :
This will round to any value not limited by powers of 10.
extension Double {
func roundToNearestValue(value: Double) -> Double {
let remainder = self % value
let shouldRoundUp = remainder >= value/2 ? true : false
let multiple = floor(self / value)
let returnValue = !shouldRoundUp ? value * multiple : value * multiple + value
return returnValue
}
}

NSNumberformatter add extra zero

I'm looking for a way to display "1" as "01", so basically everything below 10 should have a leading 0.
What would be the best way to do this?
I know I can just use a simple if structure to do this check, but this should be possible with NSNumberformatter right?
If you just want an NSString, you can simply do this:
NSString *myNumber = [NSString stringWithFormat:#"%02d", number];
The %02d is from C. %nd means there must be at least n characters in the string and if there are less, pad it with 0's. Here's an example:
NSString *example = [NSString stringWithFormat:#"%010d", number];
If the number variable only was two digits long, it would be prefixed by eight zeroes. If it was 9 digits long, it would be prefixed by a single zero.
If you want to use NSNumberFormatter, you could do this:
NSNumberFormatter * numberFormatter = [[NSNumberFormatter alloc] init];
[numberFormatter setPaddingPosition:NSNumberFormatterPadBeforePrefix];
[numberFormatter setPaddingCharacter:#"0"];
[numberFormatter setMinimumIntegerDigits:10];
NSNumber *number = [NSNumber numberWithInt:numberVariableHere];
----UPDATE------
I think this solves your problem:
[_minutes addObject:[NSNumber numberWithInt:i]];
return [NSString stringWithFormat:#"%02d", [[_minutes objectAtIndex:row] intValue]];
FIXED for Swift 3
let x = 999.1243
let formatter = NumberFormatter()
formatter.minimumFractionDigits = 1 // for float
formatter.maximumFractionDigits = 1 // for float
formatter.minimumIntegerDigits = 10 // digits do want before decimal
formatter.paddingPosition = .beforePrefix
formatter.paddingCharacter = "0"
let s = formatter.string(from: NSNumber(floatLiteral: x))!
OUTPUT
"0000000999.1"

Resources