How to format a float value in Objective-C - ios

- (NSString *)_stringToFloat:(NSNumber *)number {
if (number && number > 0) {
return [NSString stringWithFormat:#"%.2f",[number floatValue]];
}
return #"0.0";
}
Using:
_lblAppointmentFee.text = [[NSString alloc]initWithFormat:#"%#",[self_stringToFloat:[_dicObject objectForKeyNotNull:#"rate"]]];
How can I can return "5.21" for a value of 5.21 and return "5" for a value of 5.00?

Use an NSNumberFormatter. Set the desired fraction digits.
NSNumberFormatter *nf = [[NSNumberFormatter alloc] init];
nf.numberStyle = NSNumberFormatterDecimalStyle;
nf.minimumFractionDigits = 0;
nf.maximumFractionDigits = 2;
NSString *result = [nf stringFromNumber:#(5.12)];
This gives a result of "5.12" while:
result = [nf stringFromNumber:#(5.00)];
gives a result of "5".
This also has the added bonus of properly formatting the result based on the user's locale.

Related

How to convert this value into absolute value?

I am getting this from webservice
"rateavg": "2.6111"
now i am getting this in a string.
How to do this that if it is coming 2.6 it will show 3 and if it will come 2.4 or 2.5 it will show 2 ?
How to get this i am not getting. please help me
Try This
float f=2.6;
NSLog(#"%.f",f);
Hope this helps.
I come up with this, a replica of your query:
NSString* str = #"2.611";
double duble = [str floatValue];
NSInteger final = 0;
if (duble > 2.5) {
final = ceil(duble);
}else{
final = floor(duble);
}
NSLog(#"%ld",(long)final);
So it a case of using either ceil or floor methods.
Edit: Since you want it for all doubles:
NSString* str = #"4.6";
double duble = [str floatValue];
NSInteger final = 0;
NSInteger temp = floor(duble);
double remainder = duble - temp;
if (remainder > 0.5) {
final = ceil(duble);
}else{
final = floor(duble);
}
NSLog(#"%ld",(long)final);
check this
float floatVal = 2.6111;
long roundedVal = lroundf(floatVal);
NSLog(#"%ld",roundedVal);
plz use this
lblHours.text =[NSString stringWithFormat:#"%.02f", [yourstrvalue doubleValue]];
update
NSString *a =#"2.67899";
NSString *b =[NSString stringWithFormat:#"%.01f", [a doubleValue]];
// b will contane only one vlue after decimal
NSArray *array = [b componentsSeparatedByString:#"."];
int yourRating;
if ([[array lastObject] integerValue] > 5) {
yourRating = [[array firstObject] intValue]+1;
}
else
{
yourRating = [[array firstObject] intValue];
}
NSLog(#"%d",yourRating);
Try below code I have tested it and work for every digits,
NSString *str = #"2.7";
NSArray *arr = [str componentsSeparatedByString:#"."];
NSString *firstDigit = [arr objectAtIndex:0];
NSString *secondDigit = [arr objectAtIndex:1];
if (secondDigit.length > 1) {
secondDigit = [secondDigit substringFromIndex:1];
}
int secondDigitIntValue = [secondDigit intValue];
int firstDigitIntValue = [firstDigit intValue];
if (secondDigitIntValue > 5) {
firstDigitIntValue = firstDigitIntValue + 1;
}
NSLog(#"final result : %d",firstDigitIntValue);
Or another solution - little bit short
NSString *str1 = #"2.444";
float my = [str1 floatValue];
NSString *resultString = [NSString stringWithFormat:#"%.f",my]; // if want result in string
NSLog(#"%#",resultString);
int resultInInt = [resultString intValue]; //if want result in integer
To round value to the nearest integer use roundf() function of math.
import math.h first:
#import "math.h"
Example,
float ValueToRoundPositive;
ValueToRoundPositive = 8.4;
int RoundedValue = (int)roundf(ValueToRoundPositive); //Output: 8
NSLog(#"roundf(%f) = %d", ValueToRoundPositive, RoundedValue);
float ValueToRoundNegative;
ValueToRoundNegative = -6.49;
int RoundedValueNegative = (int)roundf(ValueToRoundNegative); //Output: -6
NSLog(#"roundf(%f) = %d", ValueToRoundNegative, RoundedValueNegative);
Read doc here for more information:
http://developer.apple.com/library/mac/#documentation/Darwin/Reference/ManPages/man3/roundf.3.html
NSString *value = #"1.23456";
float floatvalue = value.floatValue;
int rounded = roundf(floatvalue);
NSLog(#"%d",rounded);
if you what the round with greater value please use ceil(floatvalue)
if you what the round with lesser value please use floor(floatvalue)
You can round off decimal values by using NSNumberFormatter
There are some examples you can go through:
NSNumberFormatter *format = [[NSNumberFormatter alloc] init];
[format setPositiveFormat:#"0.##"];
NSLog(#"%#", [format stringFromNumber:[NSNumber numberWithFloat:25.342]]);
NSLog(#"%#", [format stringFromNumber:[NSNumber numberWithFloat:25.3]]);
NSLog(#"%#", [format stringFromNumber:[NSNumber numberWithFloat:25.0]]);
Corresponding results:
2010-08-22 15:04:10.614 a.out[6954:903] 25.34
2010-08-22 15:04:10.616 a.out[6954:903] 25.3
2010-08-22 15:04:10.617 a.out[6954:903] 25
NSString* str = #"2.61111111";
double value = [str doubleValue];
2.5 -> 3: int num = value+0.5;
2.6 -> 3: int num = value+0.4;
Set as your need:
double factor = 0.4
if (value < 0) value *= -1;
int num = value+factor;
NSLog(#"%d",num);

How to get the exact sale amount in Salesforce ios

Is there a field that returns the exact sale amount in salesforce?. Currently, i'm using the "Amount" from "Opportunity". I want to get the exact Amount (ex. 1,234.00) not the estimated amount.
Can't Find a field so i just formatted the result from Amount:
-(NSString *) convertAmount:(NSNumber *) number{
if ([number isKindOfClass:[NSNull class]]) {
number = 0;
}
unsigned long long value = [number longLongValue];
NSNumberFormatter *fmt = [[NSNumberFormatter alloc] init];
[fmt setNumberStyle:NSNumberFormatterDecimalStyle]; // to get commas (or locale equivalent)
NSString *result = [fmt stringFromNumber:#(value)];
result = [result stringByAppendingString:#".00"];
return result;
}
And to use it:
NSString * TestingVal = [self convertAmount:VALUE_FETCHED];
NSLog(#"Amount Value: %#", TestingVal);

Time Format so there's only 4 digits with a ":" in the middle

I want the concatenated NSString I have to be output in the format "00:00", the 0s being the digits in the concatenated string. And if there are not enough characters in the NSString, the other digits are made to be 0.
And if there are more than 4 digits than I want to only have the furthest right digits.
I have done this in Java before, I am assuming it's possible in Objective-C as well.
UIButton *button = sender;
NSString *concatenated = [self.input stringByAppendingString: button.titleLabel.text];
self.input = concatenated;
self.userOutput.text = self.input;
For example, I might get "89" as my concatenated string. I then want, self.input = 00:89.
OR
if I get 89374374 from my concatenated string, I then want self.input = 43:74.
I hope I am being clear
The following method should give the desired output:
- (NSString *)getFormattedTimeStringFromString:(NSString *)string
{
int input = [string intValue];
int mins = input % 100;
input /= 100;
int hours = input % 100;
return [NSString stringWithFormat:#"%02d:%02d", hours, mins];
}
You can use this by calling
self.input = [self getFormattedTimeStringFromString:concatenated];
Like this:
NSDateFormatter * df = [[NSDateFormatter alloc] init];
[df setDateFormat:#"HH:mm"];
NSString *dateTimeStr = [df stringFromDate:[NSDate date]];
if ([concatenated length] == 2) {
self.input = [NSString stringWithFormat:#"00:%#",concatenated];
}
else
{
NSString *test = [concatenated substringFromIndex:[concatenated length] -4];
self.input = [NSString stringWithFormat:#"%#:%#",[test substringToIndex:2],[test substringFromIndex:[test length]-2]];
}
Please try above code it will fail if [concatenated length] is 3 or 1 , modify it accordingly

Change numbers to text iOS [duplicate]

This question already has answers here:
How do I convert an integer to the corresponding words in objective-c?
(7 answers)
Closed 8 years ago.
I am not sure how to explain this but I need something like this and I'm not quite sure how to do it. I have a textfield where the user enters a number. For example "200". I got a label that must show "Two Hundred"(The number entered in Words )
Any ideas on how to do this?
Thanks in advance sorry for my bad english
try this:
//textField.text is 200
NSInteger someInt = [textField.text integerValue];
NSString *numberWord;
NSNumber *numberValue = [NSNumber numberWithInt:someInt];
NSNumberFormatter *numberFormatter = [[NSNumberFormatter alloc] init];
[numberFormatter setNumberStyle:NSNumberFormatterSpellOutStyle];
numberWord = [numberFormatter stringFromNumber:numberValue];
NSLog(#"numberWord= %#", numberWord); // Answer: two hundred
yourLabel.text = numberWord;
You can use a NSNumberFormatter It can convert an NSNumber into its word representation.
NSNumber* number = #100;
NSString* textNumber;
NSNumberFormatter *numberFormatter = [[NSNumberFormatter alloc] init];
[numberFormatter setNumberStyle:NSNumberFormatterSpellOutStyle];
textNumber = [numberFormatter stringFromNumber:number];
Here's something totally different. A bit more complex and weird, but you can fiddle around with it if you seek more manual control over the output. This is set up to serve a value up to 100,000 (to demonstrate a conditional set up).
Have fun:
int theInteger = 1,123;
int convert1000 = 0;
int convert100 = 0;
int convert10 = 0;
int convert1 = 0;
NSString * wordThousand = #"Thousand";
NSString * wordHundred = #"Hundred";
NSArray *wordsArraySingleDigit = [[NSArray alloc] initWithObjects:#"Zero",#"One",#"Two",#"Three",#"Four",#"Five",#"Six",#"Seven",#"Eight",#"Nine",nil];
NSArray *wordsArrayDoubleDigit = [[NSArray alloc] initWithObjects:#"Ten",#"Eleven",#"Twelve",...,#"Ninety Eight", #"Ninety Nine",nil];
convert1000 = (theInteger - (theInteger % 1000))/1000;
convert100 = ((theInteger - (convert1000 * 1000)) - ((theInteger - (convert1000 * 1000)) % 100))/100;
convert10 = ((theInteger - (convert1000 *1000)-(convert100 *100)) - ((theInteger -(convert1000 *1000) - (convert100 *100)) % 10))/10;
convert1 = (theInteger - (convert1000 *1000)-(convert100 *100) - (convert10 *10));
if (theInteger > = 10000 && < 100000){
NSString * convertedThousand = [wordsArrayDoubleDigit objectAtIndex : convert1000];
convertedThousand = [NSString stringWithFormat: #“%# %#“,convertedThousand,wordThousand];
NSLog (convertedThousand);
}
if (theInteger >= 1000 && <= 10000){
NSString * convertedThousand = [wordsArraySingleDigit objectAtIndex : convert1000];
convertedThousand = [NSString stringWithFormat: #“%# %#“,convertedThousand,wordThousand];
NSLog (convertedThousand);
}
NSString * convertedHundred = [wordsArraySingleDigit objectAtIndex : convert100];
convertedHundred = [NSString stringWithFormat: #“%# %#“, convertedHundred,wordHundred];
NSLog (convertedHundred);
NSString * convertedTen = [wordsArraySingleDigit objectAtIndex : convert10];
convertedTen = [NSString stringWithFormat: #“%#“, convertedTen];
NSLog (convertedTen);
NSString *convertedOne = [wordsArraySingleDigit objectAtIndex : convert1];
NSLog (convertedOne);
Hope this helps or gives you a starting point for an alternative approach.
I think you should account for every possibility and make a set of IF statements, for example, if the first digit of the number is 3, write "three", if the number has 4 digits, display "thousands"... of course you can organize your code to make the process easy.

Stop Float value rounding off in objective c

I have to prevent the value from rounding off after the decimal.
Here is the code I use :
NSNumberFormatter* nf = [[[NSNumberFormatter alloc] init] autorelease];
nf.positiveFormat = #"0.###";
NSString* trimmedValue = [nf stringFromNumber: [NSNumber numberWithFloat:[exRateLabel doubleValue]*amount]];
trimmedValue = [trimmedValue substringToIndex:[trimmedValue length]-1];
In this case, if I multiply 1000 * 50.1234 I'm getting 50123.3984, but it should be 50123.4.
NSLog(#".2f",50.1234*1000);
For this case it's showing the correct value but for
NSLog(#".2f",50.1234*123);
it is rounding off the actual value, which is 6165.1782, to 6165.18.
Just use double instead of float and a proper rounding rule:
NSNumberFormatter* nf = [[NSNumberFormatter alloc] init];
nf.positiveFormat = #"0.###";
nf.roundingMode = NSNumberFormatterRoundFloor;
NSString* trimmedValue = [nf stringFromNumber: [NSNumber numberWithDouble:50.1234*123]];
NSLog(#"trimmedValue: %#", trimmedValue);
And the result is:
trimmedValue: 6165.178
If the mathematics is required to be precise, I'd suggest using an NSDecimalNumber.
NSDecimalNumber *myNumber = [[NSDecimalNumber alloc] initWithMantissa:501234 exponent:-4 isNegative:NO]];
NSDecimalNumber *answer = [self multiplyDecimalNumber:myNumber with:[NSDecimalNumber decimalNumberWithMantissa:1000 exponent:0 isNegative:NO];
NSLog(#"Answer: %g", floor([answer doubleValue]));
I made a quick wrapper for the multiplication, I never wanted an exception, your needs may be different:
-(NSDecimalNumber *) multiplyDecimalNumber:(NSDecimalNumber *) lhs with:(NSDecimalNumber *) rhs {
NSDecimalNumberHandler *handler = [NSDecimalNumberHandler decimalNumberHandlerWithRoundingMode:NSRoundPlain scale:NSDecimalNoScale raiseOnExactness:NO raiseOnOverflow:NO raiseOnUnderflow:NO raiseOnDivideByZero:NO];
return [lhs decimalNumberByMultiplyingBy:rhs withBehavior:handler];
}
They are both correct.
First, I believe you have a typo - you're missing the %.
NSLog(#"%.2f", 50.1234*1000); // same as #"%.2f", 50,123.4 = #"50123.4"
the math leaves you with a clean 1/10th, even though you are asking for 2 decimal places to be printed.
NSLog(#"%.2f",50.1234*123); // same as #"%.2f", 5,161.1782 = #"5161.18"
you are asking for two decimal numbers and rounding up is the default behavior.
It sounds like the formatting you actually want to use is:
NSLog(#"%.1f", number);
or if you want a forced, zero-padded two digits, use
NSLog(#"%.02", number); // first case would come out #"50123.40"
this will force all trailing zeros to be printed
you are probably using a 'double' representation, cast the number to a float or you can use your own policy for truncation using functions like:
float roundUp (float value, int digits) {
int mod = pow(10, digits);
float roundedUp = value;
if (mod != 0) {
roundedUp = ceilf(value * mod) / mod;
}
return roundedUp;
}
float roundDown (float value, int digits) {
int mod = pow(10, digits);
float roundedDown = value;
if (mod != 0) {
roundedDown = floorf(value * mod) / mod;
}
return roundedDown;
}
float nearestf (float value, int digits) {
int mod = pow(10, digits);
float nearest = value;
if (mod != 0) {
nearest = floorf(value*mod + 0.5) / mod;
}
return nearest;
}
'roundUp' should be the one you need, or try with the more generic 'nearestf'
For me it was requirement to show atleast two decimal and maximum decimal number.
Following code did worked for me.
NSNumberFormatter *numberFormatter = [[NSNumberFormatter alloc] init];
[numberFormatter setNumberStyle:NSNumberFormatterDecimalStyle];
[numberFormatter setMaximumFractionDigits:2];
[numberFormatter setMinimumFractionDigits:2];
[numberFormatter setRoundingMode:NSNumberFormatterRoundDown];
NSString *num = #"123456.019";
NSString *stringFromNumber = [numberFormatter stringFromNumber:[numberFormatter numberFromString:num]];
NSLog(#"check this %#", stringFromNumber);

Resources