How to get the exact sale amount in Salesforce ios - 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);

Related

Convert numbers to currency

I have number 36381129. I need number 36.381,129
I tried this code, but it doesn't work.
int number = 36381129;
NSNumberFormatter *numberFormatter = [[NSNumberFormatter alloc] init];
[numberFormatter setNumberStyle: NSNumberFormatterCurrencyStyle];
NSString *numberAsString = [numberFormatter stringFromNumber: [NSNumber numberWithInt:number]];
I give this number.
36.381.129,00 $
I think this is BRAZILIAN REAL CURRENCY Format. You have to call this method with your price in float value, and this method returns your string into your format. Like if we pass 123456789, then it will return 123,456,789.00.
//Convert Price to Your Price Format
+(NSString*)convertFormat:(float)value{
NSString * convertedString = [NSString stringWithFormat:#"%.2f", value];
NSString * leftPart;
NSString * rightPart;
if (([convertedString rangeOfString:#"."].location != NSNotFound)) {
rightPart = [[convertedString componentsSeparatedByString:#"."] objectAtIndex:1];
leftPart = [[convertedString componentsSeparatedByString:#"."] objectAtIndex:0];
}
//NSLog(#"%d",[leftPart length]);
NSMutableString *mu = [NSMutableString stringWithString:leftPart];
if ([mu length] > 3) {
[mu insertString:#"." atIndex:[mu length] - 3];
//NSLog(#"String is %# and length is %d", mu, [mu length]);
}
for (int i=7; i<[mu length]; i=i+4) {
[mu insertString:#"." atIndex:[mu length] - i];
//NSLog(#"%d",mu.length);
}
convertedString = [[mu stringByAppendingString:#","] stringByAppendingString:rightPart];
return convertedString;
}
For more details, refer this blog.
Hope, this is what you're looking for. Any concern get back to me.
Welcome to SO. Your question is pretty vague.
Currency formats depend on the user's locale. It's generally better to either use the default locale of the device, or set a locale, and then let the currency formatter create that string that's appropriate for that locale.
If you set up a hard-coded currency format then it will be wrong for some users. (For example in the US we use a "." as a decimal separator and commas as a grouping symbol. In most of Europe they use a comma as a decimal separator and the period as a grouping symbol. Some countries put the currency symbol at the end of a currency amount, and others put it at the beginning.)
You can use this code:
NSNumberFormatter *formatter = [[NSNumberFormatter alloc] init];
[formatter setNumberStyle:NSNumberFormatterCurrencyStyle];
NSString *groupingSeparator = [[NSLocale currentLocale] objectForKey:NSLocaleGroupingSeparator];
[formatter setGroupingSeparator:groupingSeparator];
[formatter setGroupingSize:3];
[formatter setAlwaysShowsDecimalSeparator:NO];
[formatter setUsesGroupingSeparator:YES];
and use it this way:
NSString *formattedString = [formatter stringFromNumber:[NSNumber numberWithFloat:rev];
This is a generic solution and will work for any country according to their grouping separator
Taken from: https://stackoverflow.com/a/5407103/2082569

Remove negative symbol (-) from NSDecimalNumber gives me an error

I have an array with NSDecimalNumbers inside. I will do a check to see if that number is a negative number. If it is, I want to remove the negative sign (-). Here is my code:
NSString *amount = [myArray objectAtInde:2]; // Is a NSDecimalNumber with value of: -397.67
if ([amount doubleValue] < 0) {
amount = [amount stringByReplacingOccurrencesOfString:#"-" withString:#"- $"];
}
When I do that, I get the following error:
Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '-[NSDecimalNumber stringByReplacingOccurrencesOfString:withString:]: unrecognized selector sent to instance 0x7fcaf94eff80'
Add below method in your source file
// multiplies number with -1 if it is less than zero else returns the same
- (NSDecimalNumber *)abs:(NSDecimalNumber *)num
{
if ([num compare:[NSDecimalNumber zero]] == NSOrderedAscending)
{
// Number is negative. Multiply by -1
NSDecimalNumber * negativeOne = [NSDecimalNumber decimalNumberWithMantissa:1
exponent:0
isNegative:YES];
return [num decimalNumberByMultiplyingBy:negativeOne];
}
else
{
return num;
}
}
And convert instance of NSDecimalNumbers to abs value without doing any type conversion as-
NSDecimalNumbers *number = [myArray objectAtInde:2];
number = [number abs:number];
the number returned will contain abs value in NSDecimalNumbers format.
Try this,
NSDecimalNumber *amountNumber = [myArray objectAtIndex:2]; // Is a NSDecimalNumber with value of: -397.67
NSString *stringWithDollarSymbol = [self addDollarSymoblForNumber:amountNumber];
You can assign the stringWithDollarSymbol to label
- (NSString *)addDollarSymoblForNumber:(NSDecimalNumber *)decimalNum
{
NSString *modifiedString = #"";
if (decimalNum) {
NSString *numberInStringForm = [decimalNum stringValue];
if ([decimalNum doubleValue] < 0) { //adds dollor symbol for negative numbers
modifiedString = [numberInStringForm stringByReplacingOccurrencesOfString:#"-" withString:#"- $"];
}
else //adds dollor symbol for positive numbers
{
modifiedString = [NSString stringWithFormat:#"$ %#",modifiedString];
}
}
return modifiedString;
}
EDIT
More Better Approach using NSNumberFormatter:
- (NSString *)formatNumberBasedOnCurrentLocale:(NSDecimalNumber *)number
{
NSNumberFormatter *formatter = [[NSNumberFormatter alloc] init];
[formatter setLocale:[NSLocale currentLocale]];
[formatter setNumberStyle:NSNumberFormatterCurrencyStyle];
NSString *result = [formatter stringFromNumber:number];
if (result.length >0) {
return result;
}
return nil;
}
Please add line,
if ([amount doubleValue] < 0) {
amount=[NSString stringWithFormat:#"%#",[myArray objectAtIndex:2]];//add line
amount = [amount stringByReplacingOccurrencesOfString:#"-" withString:#""];
}
it may be work for you,
I just used your code & it's working fine at my end.
Tried below thing,
NSString *amount = #"-397.67";//[myArray objectAtInde:2]; // Is a NSDecimalNumber with value of: -397.67
if ([amount doubleValue] < 0) {
amount = [amount stringByReplacingOccurrencesOfString:#"-" withString:#""];
}
Try it at your end.
If nothing will work then multiply your negative float value with -1 & you will get positive number. If that is your requirement.
Your [myArray objectAtInde:2] is a NSDecimalNumber rather than NSString, try this:
NSDecimalNumber *amountNumber = [myArray objectAtInde:2];
NSString *amount = [NSString stringWithFormat:#"%#", amountNumber];
Maybe you should try this one:
NSString *amount = #(ABS([myArray[2] doubleValue])).stringValue ; // Is a NSDecimalNumber with value of: -397.67
If your intention is to rescue from the negative then just simply convert the value into an absolute value.
NSString *amount = [myArray objectAtIndex:2]; // Is a NSDecimalNumber with value of: -397.67
NSLog(#"The value is : %#",[NSString stringWithFormat:#"%.2f", fabs([amount doubleValue])]);
The value is: 397.67

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

Having trouble using NSNumberFormatter for currency conversion in iOS

I have a UITextField that receives numeric input from the user in my application. The values from this textfield then get converted into currency format using NSNumberFormatter within my shouldChangeCharactersInRange delegate method. When I enter the number "12345678", the number gets correctly converted to $123456.78 (the numbers are entered one digit at a time, and up to this point, everything works smoothly). However, when I enter another digit after this (e.g. 9), rather than displaying "1234567.89", the number "1234567.88" is displayed. If I enter another number after that, a totally different numbers after this (I'm using the number key pad in the application to enter the numbers. Here is the code that I have:
NSNumberFormatter *formatter = [[NSNumberFormatter alloc] init];
[formatter setNumberStyle:NSNumberFormatterCurrencyStyle];
modifiedValue = [formatter stringFromNumber:[NSNumber numberWithFloat:[modifiedValue floatValue]]];
textField.text = modifiedValue;
The line that causes this unusual conversion is this one:
modifiedValue = [formatter stringFromNumber:[NSNumber numberWithFloat:[modifiedValue floatValue]]];
Can anyone see why this is?
It's likely to be a rounding error when doing the string->float conversion. You shouldn't use floats when dealing with currency. You could use a NSDecimalNumber instead.
NSNumberFormatter *formatter = [[NSNumberFormatter alloc] init];
[formatter setNumberStyle:NSNumberFormatterCurrencyStyle];
// Below 2 lines if converting from a "currency" string
NSNumber *modifiedNumber = [formatter numberFromString:modifiedValue]; // To convert from the currency string to a number object
NSDecimalNumber *decimal = [NSDecimalNumber decimalNumberWithDecimal:[modifiedNumber decimalValue]];
// OR the below line if converting from a non-currency string
NSDecimalNumber *decimal = [NSDecimalNumber decimalNumberWithString:modifiedValue];
modifiedValue = [formatter stringFromNumber:decimal]; // Convert the new decimal back to a currency string
You may also consider making the number formatter lenient - often helps with user entered data.
[formatter setLenient:YES];
When I'm running number conversions to currency, I usually run this code:
- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string
{
NSString *text = _textField.text;
NSString *decimalSeperator = #".";
NSCharacterSet *charSet = nil;
NSString *numberChars = #"0123456789";
// the number formatter will only be instantiated once ...
static NSNumberFormatter *numberFormatter;
if (!numberFormatter)
{
[numberFormatter setLocale:[NSLocale currentLocale]];
numberFormatter = [[NSNumberFormatter alloc] init];
numberFormatter.numberStyle = NSNumberFormatterCurrencyStyle;
numberFormatter.maximumFractionDigits = 10;
numberFormatter.minimumFractionDigits = 0;
numberFormatter.decimalSeparator = decimalSeperator;
numberFormatter.usesGroupingSeparator = NO;
}
// create a character set of valid chars (numbers and optionally a decimal sign) ...
NSRange decimalRange = [text rangeOfString:decimalSeperator];
BOOL isDecimalNumber = (decimalRange.location != NSNotFound);
if (isDecimalNumber)
{
charSet = [NSCharacterSet characterSetWithCharactersInString:numberChars];
}
else
{
numberChars = [numberChars stringByAppendingString:decimalSeperator];
charSet = [NSCharacterSet characterSetWithCharactersInString:numberChars];
}
// remove amy characters from the string that are not a number or decimal sign ...
NSCharacterSet *invertedCharSet = [charSet invertedSet];
NSString *trimmedString = [string stringByTrimmingCharactersInSet:invertedCharSet];
text = [text stringByReplacingCharactersInRange:range withString:trimmedString];
// whenever a decimalSeperator is entered, we'll just update the textField.
// whenever other chars are entered, we'll calculate the new number and update the textField accordingly.
if ([string isEqualToString:decimalSeperator] == YES)
{
textField.text = text;
}
else
{
NSNumber *number = [numberFormatter numberFromString:text];
if (number == nil)
{
number = [NSNumber numberWithInt:0];
}
textField.text = isDecimalNumber ? text : [numberFormatter stringFromNumber:number];
}
return NO; // we return NO because we have manually edited the textField contents.
}
The link explaining this is Re-Apply currency formatting to a UITextField on a change event
Hope this works!

Set UILabel character limit?

I have a UILabel that shows the outside temperature, the problem is, sometimes it shows it as a XX.XXº format instead of the normal XXº or XXXº format used to show temperature, is there anyway to force the label to only show the temperature without the decimals or at least force it to only be able to use 2 characters?
You can use this to eliminate the decimals:
NSString* numberString = [NSString stringWithFormat:#"%.0f", d]; // 0 means no decimals
Otherwise I believe this will work to limit the number of chars to 2:
NSNumberFormatter *formatter = [[NSNumberFormatter alloc] init];
formatter.usesSignificantDigits = YES;
formatter.maximumSignificantDigits = 2;
I have not really used NSNumberFormatter very much though.
NSString *temp = [galleryEntryTree objectForKey:#"description"];
if ([temp length] > 500) {
NSRange range = [temp rangeOfComposedCharacterSequencesForRange:(NSRange){0, 500}];
temp = [temp substringWithRange:range];
temp = [temp stringByAppendingString:#" …"];
}
coverView.label2.text = temp;
You may also use substring method
NSString *newformat = [NSString stringWithFormat:#"%#",[temperature substringWithRange:NSMakeRange(0,2)]];
In this case temperature is a string that you set for your label and you are only retrieving the 1st 2 digits only

Resources