Sneha Sneha - 5 months ago 31
Objective-C Question

%g gives Exponential Form of Value in ios

My Requirement

There is one label having Price Value (Float Value)

If it is -> Then It should be

1232.200 -> 1232.2

1232.243 -> 1232.243

1232.00 -> 1232

What I had Done till Now

1) Used %.2f

lblPrice.text=[NSString stringWithFormat:@"%.2f",myValue];


But it always give 2 digits after points like
1232.20
,
1232.24
,
1232.00
Respectively...

2) So then I change
%.2f
to
%g


lblPrice.text=[NSString stringWithFormat:@"%g",myValue];


That Gives Perfect Value for all The above requirement, But when the value exceeds to some level , It is converted to exponential form like this..

If myValue is
1189243.609
then It results in
1.18924e+06

Which I don't want..

Any Solution for this???
Thanks in Advance..

Answer

I just test the following code and that work as per your requirement hope that help:

NSNumberFormatter *NumberFormate = [[NSNumberFormatter alloc] init];
[NumberFormate setRoundingIncrement:[NSNumber numberWithDouble:0.001]];
[NumberFormate setMaximumFractionDigits:4];
[NumberFormate setMinimumFractionDigits:0];

NSLog(@"232.200 IS %@", [NumberFormate stringFromNumber:[NSNumber numberWithFloat:1232.200]]);
NSLog(@"1232.243 IS %@", [NumberFormate stringFromNumber:[NSNumber numberWithFloat:1232.243]]);
NSLog(@"1232.00 IS %@", [NumberFormate stringFromNumber:[NSNumber numberWithFloat:1232.00]]);

It's output is :

enter image description here

Comments