Objective-C: Double to NSString with x-many decimals - objective-c

I know that I can cast a double to a NSString with a specific amount of decimals like so:
double myDouble = 123.456789;
NSString *myString = [NSString stringWithFormat:#"%.4g", myDouble];
But how can I replace the number "4" in this example with a int variable?
Something like this doesn't work:
double myDouble = 123.456789;
int precision = 4;
NSString *myString = [NSString stringWithFormat:#"%.%dg", myDouble, precision];

Consider using NSNumberFormatter:
double myDouble = 123.456789;
int precision = 4;
NSNumberFormatter *formatter = [[NSNumberFormatter alloc] init];
formatter.minimumFractionDigits = precision;
formatter.maximumFractionDigits = precision;
NSString *myString = [formatter stringFromNumber:#(myDouble)];
Or, if you want this in scientific notation, you can alternatively specify something like:
formatter.numberStyle = NSNumberFormatterScientificStyle;
formatter.usesSignificantDigits = YES;
formatter.minimumSignificantDigits = precision;
formatter.maximumSignificantDigits = precision;
It just depends upon what precisely you're looking for.
This also has the virtue of also honoring the user's regional settings (e.g. if in Germany, the decimal separator is a comma, not a period).
If you need to force the locale setting (e.g. this is for creating something that will be exchanged with a web service that expects the data in a specified format), you can set the formatter's locale (e.g. [NSLocale localeWithLocaleIdentifier:#"en_US"]). But when presenting results in the user interface, you always want to honor the device's locale settings.

You can use asterisk in place of optional width and precision specifiers. And set them as arguments
double myDouble = 123.456789;
int width = 10;
int precision = 6;
NSString *s = [NSString stringWithFormat:#"%*.*g", width, precision, myDouble];

If you follow the links in the documentation for stringWithFormat you will discover the IEEE printf specification which describes the formats supported. That tells you that a field width or precision can be an * to indicate the actual value is supplied an an int argument, so what you want is:
NSString *myString = [NSString stringWithFormat:#"%.*g", intPrecision, myDouble];

double myDouble = 123.456789;
int precision = 4;
NSString *myString = [NSString stringWithFormat:#"%.*f", precision, myDouble];
NSLog(#"myString: '%#'", myString);
NSLog output:
myString: '123.4567'

This is by no means an optimal way of doing it, but it is a way.
You can do it in multiple steps
NSString *val = [NSString stringWithFormat: #"%d", 4];
NSString *head = [#"%." stringByAppendingString: val];
NSString *format = [head stringByAppendingString: #"g"];
NSString *result = [NSString stringWithFormat: format, 123.456789];
Or if you're really adventurous (for the sake of readability, don't EVER do this):
NSString *result = [NSString stringWithFormat: [[#"%." stringByAppendingString: [NSString stringWithFormat: #"%d", 4]] stringByAppendingString: #"g"], 123.456789];

Related

How can i decrement an NSString's Value from a UITextField Value input by user?

I am trying to decrement an NSString value which may hold a saved amount (Ex: 560.00)
and when the user enters a value into a UITextField Object, say, 50.00, the NSString holding the value of 560.00 decrements to 510.00 from 50.00 and still holds the Value without deleting the entire value or setting it to 50.00 ?
Use NSNumberFormatter to parse NSString value to NSNumber and reverse. In addition it will allow you to handle user's locale.
Basic example:
NSNumberFormatter *numberFormatter = [[NSNumberFormatter alloc] init];
NSNumber *numberFromString = [numberFormatter numberFromString:userInput];
double valueAfterDecrement = [numberFromString doubleValue] - delta;
NSString *stringFromNumber = [numberFormatter stringFromNumber:#(valueAfterDecrement)];
here a basic example.
NSString *string = #"50.22";
float number=[string floatValue];
NSLog(#"%f",number);
NSString *string1 = #"560.22";
float number1=[string1 floatValue];
NSLog(#"%f",number1);
float ans = number1 - number;
NSLog(#"%f",ans);
NSString * finalStr = [NSString stringWithFormat:#"%f",ans];

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...

Convert float value to NSString

Do you know how can i convert float value to nsstring value because with my code, there is an error.
My Code :
- (float)percent:(float)a :(float)b{
return a / b * 100;
}
- (void)objectLoader:(RKObjectLoader*)objectLoader didLoadObjects:(NSArray*)objects {
// ....
float tx_nb_demande_portabilite = [self percent: [(NSNumber*) [stat nb_demande_portabilite] floatValue] :[(NSNumber*) [stat nb_users] floatValue]];
NSString *tx_nb_demande_portabilite_st = [NSString stringWithFormat:#"%#", tx_nb_demande_portabilite];
//....
}
The error :
EXC_BAD ACCESS for NSString *tx_nb_demande_portabilite_st = [NSString stringWithFormat:#"%#", tx_nb_demande_portabilite];
Thank you for your help.
You need to use %f format specifier for float, not %#.
NSString *str = [NSString stringWithFormat:#"%f", myFloat];
To use specific number of digits after decimal use %.nf where n is number of digits after decimal point.
// 3 digits after decimal point
NSString *str = [NSString stringWithFormat:#"%.3f", myFloat];
Obj-C uses C printf style formatting. Please check printf man page for all other possible formatting.
one more option:
NSString * str = [NSNumber numberWithFloat:value].stringValue;
#"%f" sounds like more appropriate format string for float.
[NSString stringWithFormat:#"%f", tx_nb_demande_portabilite];
A modern (and less verbose) approach would be:
NSString *str = #(myFloat).description;

Objective-c convert Long and float to String

I need to convert two numbers to string in Objective-C.
One is a long number and the other is a float.
I searched on the internet for a solution and everyone uses stringWithFormat: but I can't make it work.
I try
NSString *myString = [NSString stringWithFormat: #"%f", floatValue]
for 12345678.1234 and get "12345678.00000" as output
and
NSString *myString = [NSString stringWithFormat: #"%d", longValue]
Can somebody show me how to use stringWithFormat: correctly?
This article discusses how to use various formatting strings to convert numbers/objects into NSString instances:
String Programming Guide: Formatting String Objects
Which use the formats specified here:
String Programming Guide: String Format Specifiers
For your float, you'd want:
[NSString stringWithFormat:#"%1.6f", floatValue]
And for your long:
[NSString stringWithFormat:#"%ld", longValue] // Use %lu for unsigned longs
But honestly, it's sometimes easier to just use the NSNumber class:
[[NSNumber numberWithFloat:floatValue] stringValue];
[[NSNumber numberWithLong:longValue] stringValue];
floatValue has to be a double. At least this compiles correctly and does what is expected on my machine
Floats can only store about 8 decimal digits and your number 12345678.1234 requires more precision than that, hence only about the 8 most significant digit are stored in a float.
double floatValue = 12345678.1234;
NSString *myString = [NSString stringWithFormat: #"%f", floatValue];
results in
2011-11-04 11:40:26.295 Test basic command line[7886:130b] floatValue = 12345678.123400
You should use NSNumberFormatter eg:
NSNumberFormatter * nFormatter = [[NSNumberFormatter alloc] init];
[nFormatter setNumberStyle:NSNumberFormatterDecimalStyle];
NSNumber *num = [nFormatter numberFromString:#"12345678.1234"];
[nFormatter release];

How to convert int to NSString?

I'd like to convert an int to a NSString in Objective C.
How can I do this?
Primitives can be converted to objects with #() expression. So the shortest way is to transform int to NSNumber and pick up string representation with stringValue method:
NSString *strValue = [#(myInt) stringValue];
or
NSString *strValue = #(myInt).stringValue;
NSString *string = [NSString stringWithFormat:#"%d", theinteger];
int i = 25;
NSString *myString = [NSString stringWithFormat:#"%d",i];
This is one of many ways.
If this string is for presentation to the end user, you should use NSNumberFormatter. This will add thousands separators, and will honor the localization settings for the user:
NSInteger n = 10000;
NSNumberFormatter *formatter = [[NSNumberFormatter alloc] init];
formatter.numberStyle = NSNumberFormatterDecimalStyle;
NSString *string = [formatter stringFromNumber:#(n)];
In the US, for example, that would create a string 10,000, but in Germany, that would be 10.000.