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
Related
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);
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);
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);
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
Merging these two strings:
#"###.##"
#"123"
Should output:
#"1.23"
I have developed a solution for this, but I'm looking for a simpler way, Using a NSNumberFormater, or some other API that I might be missing in Apple's documentation.
Thank you!
-
The solution as is right now, that I'm trying to get rid of:
/**
* User inputs a pure, non fractional, numeric string (e.g 1234) We'll see how many fraction digits it needs and format accordingly (e.g. 1234 produces a string such as '12.34' for 2 fractional digits. 12 will produce '0.12'.)
*
* #return The converted numeric string in an instance of NSDecimalNumber
*/
- (NSDecimalNumber *)decimalNumberFromRateInput
{
if (_numericInput == nil ||
_numericInput.length == 0) {
_numericInput = #"0";
}
[self clearLeadingZeros];
if (self.formatter == nil) {
return nil;
}
if (self.formatter.maximumFractionDigits == 0) {
return [NSDecimalNumber decimalNumberWithString:_numericInput];
}
else if (_numericInput.length <= self.formatter.maximumFractionDigits) {
NSString *zeros = #"";
for (NSInteger i = _numericInput.length; i < self.formatter.maximumFractionDigits ; i++) {
zeros = [zeros stringByAppendingString:#"0"];
}
NSString *decimalString = [NSString stringWithFormat:#"0.%#%#",zeros,_numericInput];
return [NSDecimalNumber decimalNumberWithString:decimalString];
}
else {
NSString *decimalPart = [_numericInput substringToIndex: _numericInput.length - self.formatter.maximumFractionDigits];
NSString *fractionalPart = [_numericInput substringFromIndex:_numericInput.length - self.formatter.maximumFractionDigits];
NSString *decimalString = [NSString stringWithFormat:#"%#.%#", decimalPart, fractionalPart];
return [NSDecimalNumber decimalNumberWithString: decimalString];
}
}
If I understand your goal correctly, the solution should be much simpler:
float number = [originalString floatValue] / 100.0;
NSString *formattedString = [NSString stringWithFormat:#"%.2f", number];