How to display leading zero in double - objective-c

I need to make NSNumber to display only 4 decimal points. This part of code is works, but it outputs result without leading zero.
double resultRoundToDecimal = [result doubleValue];
NSNumberFormatter *resultFormatter = [[NSNumberFormatter alloc] init];
[resultFormatter setRoundingMode:NSNumberFormatterRoundHalfUp];
[resultFormatter setMaximumFractionDigits:4];
resultData = [resultFormatter stringFromNumber:[NSNumber numberWithDouble:resultRoundToDecimal]];
For example:
1/3 = .3333
I want:
1/3 = 0.3333
How I can to do this?

You could choose to use string formatter too, like below
float val=1./3;
NSString *resultData=[NSString stringWithFormat:#"%0.4f",val];
NSLog(#"Result = %#",resultData);

Prepend a 0 or use number formatter.
NSString *printStr = #"0";
printStr = [NSString stringByAppendingString: resultData];
Otherwise, you could use a number formatter or something similar. If your just outputting a string why not do that?
https://developer.apple.com/library/mac/#documentation/Cocoa/Reference/Foundation/Classes/NSNumberFormatter_Class/Reference/Reference.html

Related

Output A Float Without Zero Before Decimal Point

I'm wondering how a float that has a zero followed by a decimal followed by numbers like this:
0.45
...to ditch the zero that's in front of the decimal point like this:
.45
within a NSString using the [NSString stringWithFormat:] method using Objective C.
You can't directly eliminate the leading 0 when formatting a floating point value using stringWithFormat: and %f. You will have to remove it yourself from the result:
NSString *result = [NSString stringWithFormat:#"%.2f", 0.45];
if ([result hasPrefix:#"0."]) {
result = [result substringFromIndex:1];
}
But a better solution is to use NSNumberFormatter. Set minimumIntegerDigits to 0 to avoid the leading 0.
NSNumberFormatter *fmt = [[NSNumberFormatter alloc] init];
fmt.numberStyle = NSNumberFormatterDecimalStyle;
fmt.minimumInterDigits = 0;
NSString *result = [fmt stringFromNumber:#(0.45)];
This has the advantage of formatting the result properly for the user's locale (other than removing the leading 0).
It may best to avoid removing the leading 0. The output may be confusing to users.

Not seeing the decimal from a string when converted into NSDecimalNumer

I can't see to find the answer to this, but I have a string that has a decimal point in it, and when I try to convert it to a NSDecimalNumber I only get back the whole number, not the decimal or what would come after it. This is what I am trying:
someText.text = #"200.00";
tempAmountOwed = [NSDecimalNumber decimalNumberWithString:someText.text]; // gives me back 200
I can't seem to figure out if the decimalNumberWithString method is stripping out my decimal and ignoring what comes after it.
Thanks for the help!
You can use the method decimalNumberWithString: locale: method.
for eg:-
The code:
NSLog(#"%#", [NSDecimalNumber decimalNumberWithString:#"200.00"]);
NSLog(#"%#", [NSDecimalNumber decimalNumberWithString:#"200.00" locale:NSLocale.currentLocale]);
Gives following log:
200
200.00
Hope this Helps!
That's perfectly normal. If your decimal String doesn't contain fractions it won't print them. If you want to print them you can use a NSNumberFormatter or convert it to a float and print it with %.2f to do so:
NSString *text = #"200.00";
NSDecimalNumber *number = [NSDecimalNumber decimalNumberWithString:text];
NSLog(#"%#", number); //this will print "200"
//solution #1
NSNumberFormatter *numberFormatter = [[NSNumberFormatter alloc] init];
numberFormatter.numberStyle = NSNumberFormatterDecimalStyle;
numberFormatter.minimumFractionDigits = 2;
NSLog(#"%#", [numberFormatter stringFromNumber:number]); //this will print "200.00"
//solution #2
CGFloat number = [text floatValue];
NSLog(#"%.2f", number); //this will print "200.00"

How do I combine a char with an int in an NSTextField in Objective-C?

For example, I have the following code, where lblPercent is an NSTextField:
double Progress = progress( Points);
[lblPercent setIntValue:(Progress)];
I set it as integer value so it tosses out the decimal, since for some reason the NSProgressIndicator forces me to use a double. Anyway, in the label adjacent to the progress bar, I want it see the number x% with the percent sign next to it.
I tried standard concatenation techniques but no dice.
You should use an NSNumberFormatter with the percent style
NSNumberFormatter* formatter = [[NSNumberFormatter alloc] init];
[formatter setNumberStyle: NSNumberFormatterPercentStyle];
// Any other format settings you want
NSString* formattedNumber = [formatter stringFromNumber: [NSNumber numberWithDouble: progress]];
try
[lblPercent setText:[NSString stringWithFormat:#"%d%%",[Progress intValue]]];
NSMutableString *value = lblPercent.text;
[value appendString:#"%"];
[lblPercent setText:value];
You can use unicode characters to get the percent sign.
i.e.
double value;
myLabel.text = [NSString stringWithFormat:#"%d\u0025", value ]
u0025 is the unicode character for 'percent sign'
NSInteger percentageProgress = (NSInteger) (Progress * 100);
[lblPercent setText:[NSString stringWithFormat:#"%d%%", percentageProgress]];
NSString *string = [NSString stringWithFormat:#"%.0f%#",Progress, #"%"];
[lblPercent setStringValue:string];
This seems to had worked for me doing it the way I had done it...

How to convert NSString to NSInteger in iPhone application?

NSString * addString=[arrayyyy componentsJoinedByString:#","];
NSLog(#"add string is: %#",addString);// result is: 45,1
Now I want to convert above string into integer.
I have tried this:
NSInteger myInt=[addString intValue];
//NSLog(#"myInt is: %d",myInt);// result is: 45
If you expected 45.1 then there are two things wrong :
45.1 is not an integer. You would have to use floatValue to read the value.
45,1 (notice the comma) is not a valid float number. While 45,1 is valid in some locale (i.e. in french its 1 000,25 instead of 1,000.25) you would have to convert the string with an NSNumberFormatter before reading the floatValue.
.
// Can't compile and verify this right now, so please bear with me.
NSString *str = #"45,1";
NSNumberFormatter *formatter = [[[NSNumberFormatter alloc] init] autorelease];
NSLocale *locale = [[[NSLocale alloc] initWithLocaleIdentifier:#"fr_FR"] autorelease]; // lets say French from France
[formatter setNumberStyle:NSNumberFormatterDecimalStyle];
[formatter setLocale:locale];
float value = [[formatter numberFromString:str] floatValue]; // value = 45.1
Try out NSExpression which works with mathematical symbols too (i.e. +, -, /, *):
NSNumber *numberValue = [[NSExpression expressionWithFormat:inputString] expressionValueWithObject:nil context:nil];
// do something with numberValue
From reading the question a lot, I think I may understand what you want.
The starting point seems to be:
NSLog(#"add string is: %#",addString);// result is: 45,1
And the current ending point is:
NSLog(#"myInt is: %d",myInt);// result is: 45
But it seems that you still want to print out 45,1
My guess on this is that you have an array of 2 strings [#"45",#"1"] called arrayyyy and you want to print out both values as integers. If this is so then what I think you want is:
NSInteger myInt1 = [[arrayyyy objectAtIndex:0] intValue];
NSInteger myInt2 = [[arrayyyy objectAtIndex:1] intValue];
NSLog(#"add string is: %d,%d",myInt1,myInt2);
Note This will crash horribly with an NSRangeException if there are not at least two strings in the array. So at the very least you should do:
NSInteger myInt1 = -1;
NSInteger myInt2 = -1;
if ([arrayyyy length] >0) myInt1 = [[arrayyyy objectAtIndex:0] intValue];
if ([arrayyyy length] >1) myInt2 = [[arrayyyy objectAtIndex:1] intValue];
NSLog(#"add string is: %d,%d",myInt1,myInt2);
But even this is bad as it assumes that the guard value of -1 will not be present in the actual data.

Why aren't the decimals printed to the string?

In order to get a string with 2 decimals value I've tried:
[[NSString stringWithFormat:#"%.2f",[[self CurrentValue] doubleValue]]]
this
[self CurrentValue] stringValue]
and this:
NSNumberFormatter *formatter = [[NSNumberFormatter alloc] init];
formatter.numberStyle = NSNumberFormatterCurrencyStyle;
NSString *string = [formatter stringFromNumber:[self CurrentValue]];
[formatter release];
But it doesn't work. THe original number is a float = 22, and I always get a string "22", and not "22.00".
Thanks
I ran a few test scenarios and hopefully this can help you get to the bottom of it. The formatter is ideal if you are doing a currency, otherwise string1 is ideal. To work from this example you can set number up - NSNumber * number = [self CurrentValue];
NSNumber * number = [NSNumber numberWithInt:22];
NSString * string1 = [NSString stringWithFormat:#"%.2f",[number doubleValue]];
NSNumberFormatter *formatter = [[NSNumberFormatter alloc] init];
formatter.numberStyle = NSNumberFormatterCurrencyStyle;
NSString *string2 = [formatter stringFromNumber:number];
[formatter release];
NSLog(#"string 1 %#\nstring 2 %#\nstring 3 %#", string1, string2, [number stringValue]);
//output
string 1 22.00
string 2 $22.00
string 3 22
// top code with NSNumber * number = [NSNumber numberWithFloat:22];
string 1 22.00
string 2 $22.00
string 3 22
// top code with NSNumber * number = [NSNumber numberWithFloat:22.0];
string 1 22.00
string 2 $22.00
string 3 22
Summary:
The way the number is created is not significant here to the output if it is truly an int (floats with such as 4.20 will work as expected in every case, but every int value 22,22.0,22.000 gets treated the same by all 3 ways of creating a number. So choose the format you like best and implement that.
Seems you have extra [] around. You can try
[NSString stringWithFormat:#"%.2f",[[self CurrentValue] floatValue]]
or
[NSString stringWithFormat:#"%.2lf",[[self CurrentValue] doubleValue]] both are good to go.
It actually much simpler.
You said that "The original number is a float = 22". Now, remember that obj-c runtime class may differ from declared one. And when you instantiate your float variable with actually integer value - it is an integer one at runtime! You should change it to one of the following:float someFloatValue = 22f;float someFloatValue = 22.0;float someFloatValue = (float)22; (not sure about that one thought)
Happy coding...