Rounded of a float with a decimal - objective-c

Do someone know if there is a method in order to round a float two numbers after the comme.
Examples :
10.28000 -> 10.3
13.97000 -> 14.0
5.41000 -> 5.4
Thanks a lot !
Regards,
Sébastien ;)

Use NSNumberFormatter to create a string with the specified faction digits.
float num = 10.28000;
formatter = [[NSNumberFormatter alloc] init];
[formatter setMaximumFractionDigits:1];
NSNumber *value = [NSNumber numberWithFloat:num];
NSString *newNumString = [formatter stringFromNumber:value];

Try this:
float aFloatValue = 3.1415926;
NSString *formatted = [NSString stringWithFormat:#"%01.1f", aFloatValue];
NSLog(#"Formatted: %#", formatted);
Think of it as a good old sprintf.

you could also try
float num = 10.28000
float result = (roundf(num * 10.0))/10.0;
(multiply by 10, then round, then divide by 10 again)
don't forget the .0 so that the division is by a float and not by an integer, which will round it again

The pure Cocoa way with NSRoundPlain behaviour:
- (NSDecimalNumber *)decimalNumberForFloat:(float)f_
{
NSNumber *number = [NSNumber numberWithFloat:f_];
NSDecimal decimal = [number decimalValue];
NSDecimalNumber *originalDecimalNumber = [NSDecimalNumber decimalNumberWithDecimal:decimal];
NSDecimalNumberHandler *roundingBehavior = [NSDecimalNumberHandler decimalNumberHandlerWithRoundingMode:NSRoundPlain
scale:0
raiseOnExactness:NO
raiseOnOverflow:NO
raiseOnUnderflow:NO
raiseOnDivideByZero:NO];
return [originalDecimalNumber decimalNumberByRoundingAccordingToBehavior:roundingBehavior];
}
since NSDecimalNumber is a subclass of NSNumber, to obtain the primitive float call -[NSDecimalNumber floatValue]

Try this out:
float myFloat = 10.4246f;
myFloat = ((int) ((myFloat * 100) + 5)) / 100.0f;

float fval = 1.54f;
float nfval = ceilf(fval * 10.0f + 0.5f)/10.0f;

Related

i get data in meter in nsnumber from api but how will i convert it into km

my code is below
NSNumber *someNumber = [[_dict2 objectForKey:#"location"] objectForKey:#"distance"];
NSString *someString = [someNumber stringValue];
_lbldistance.text=someString;
If you even want to include km in the string use NSLengthFormatter
NSNumber *someNumber = #1568;
NSLengthFormatter *formatter = [[NSLengthFormatter alloc] init];
NSString *distanceInKM = [formatter stringFromMeters:someNumber.doubleValue];
NSLog(#"%#", distanceInKM); // 1.568 km
That's rather simple: Divide by 1000.
By divide someNumber with 1000.
NSNumber *someNumber = [[_dict2 objectForKey:#"location"] objectForKey:#"distance"];
someNumber = [someNumber floatValue] * 1000;
NSString *someString = [someNumber stringValue];
1 meter is equal to 0.001 KM (as 1/1000 = 0.001).
So you can just multiply the value you receive from API with 0.001 and you will get the answer in KMs.
NSNumber *someNumber = [[_dict2 objectForKey:#"location"] objectForKey:#"distance"];
float convertedToKM = [someNumber floatValue]*0.001;
someNumber = [NSNumber numberWithFloat:convertedToKM];
NSString *someString = [someNumber stringValue];
_lbldistance.text=someString;
Since you are displaying the result, it would be better to limit it to two decimal places as is the standard practice. You can do it like:
NSNumber *someNumber = [[_dict2 objectForKey:#"location"] objectForKey:#"distance"];
float convertedToKM = [someNumber floatValue]*0.001;
NSString *someString = [NSString stringWithFormat:#"%.02f", convertedToKM];
_lbldistance.text=someString;

How to convert NSString value #"3.45" into float?

How to convert NSString value #"3.45" into float. 3.45
float fCost = [[NSDecimalNumber decimalNumberWithString:#"3.45"]floatValue] ;
NSString *val = #"3.45";
float fCost = [val floatValue];
float number = [string floatValue];
NSString's: - (float)floatValue;
For example:
NSString *str = #"3.45";
float f = [str floatValue];
Reading your comment to Marek's answer it looks like your string actually = #"$3.45"
To convert that to a float use:
NSNumberFormatter * formatter = [[[NSNumberFormatter alloc] init] autorelease];
formatter.numberStyle = NSNumberFormatterCurrencyStyle;
formatter.currencyCode = #"USD";
float value = [[formatter numberFromString: #"$3.45"] floatValue];

iPhone - Rounding a float does not work

I can't achieve rounding a float.
Those calls all returns me 3.5999999 and not 3.6 for theoTimeoutTrick and theoTimeout.
How may I achieve to get that 3.6 value, into NSString AND float vars ?
#define minTimeout 1.0
#define defaultNbRetry 5
float secondsWaitedForAnswer = 20.0;
float minDelayBetween2Retry = 0.5;
int theoNbRetries = defaultNbRetry;
float theoTimeout = 0.0;
while (theoTimeout < minTimeout && theoNbRetries > 0) {
theoTimeout = (secondsWaitedForAnswer - (theoNbRetries-1)*minDelayBetween2Retry) / theoNbRetries;
theoNbRetries--;
}
float theoTimeoutTrick = [[NSString stringWithFormat:#"%.1f", theoTimeout] floatValue];
theoTimeout = roundf(theoTimeout * 10)/10.0;
From Rounding numbers in Objective-C:
float roundedValue = round(2.0f * number) / 2.0f;
NSNumberFormatter *formatter = [[NSNumberFormatter alloc] init];
[formatter setMaximumFractionDigits:1];
[formatter setRoundingMode: NSNumberFormatterRoundDown];
NSString *numberString = [formatter stringFromNumber:[NSNumber numberWithFloat:roundedValue]];
[formatter release];
That will get you a rounded string. You can parse it back into a float I'm sure.
Okay, here's some test code and some results:
NSLog(#"%f", round(10*3.56)/10.0);
=>3.600000
NSLog(#"%f", round(10*3.54)/10.0);
=>3.500000
NSLog(#"%f", round(10*3.14)/10.0);
=>3.100000
Okay, you know what? Your original code works as intended on my machine, OSX 10.6 and Xcode 4. How exactly are you seeing your output?

Convert a number with a comma into a number with point. (Cocoa Touch)

I'm trying to code a calculator with XCode, but then I saw that Numbers with a comma are just cutted of after the comma.
I am getting the Numbers with this code out of the textfield.
-(IBAction)Additionbutton:(id)sender{
NSString *firstString = field1.text;
NSString *secondString = field2.text;
float num1;
float num2;
float output;
num1 = [firstString floatValue];
num2 = [secondString floatValue];
output = num1 + num2
Solutionfield.text = [ [NSString alloc] initWithFormat:#"%.2f",output] ;
Is it possible to set the calculation that way, that it is able to handle points AND commas or do I have to convert them and if so, how can I do this?
Thank you :)
Maybe you should use: NSNumberFormatter
How to convert an NSString into an NSNumber
I have experienced the same thing this morning, following solution worked for me:
NSNumberFormatter *numberFormatter = [[NSNumberFormatter alloc] init];
NSNumber *aNumber = [NSNumber numberWithFloat:[[yourFloatAsString stringByReplacingOccurrencesOfString:#"," withString:#"" ] floatValue]];
[numberFormatter setNumberStyle:kCFNumberFormatterDecimalStyle];
NSString *formattedNumber;
formattedNumber = [numberFormatter stringFromNumber:aNumber];
NSLog(#"formattedNumber: %#", formattedNumber);
Obviously not the most efficient solution possible. It works, but if you have some time I strongly suggest you to have a look at NSNumberFormatter Class Reference

How do I round a NSNumber to zero decimal spaces

How do I round an NSNumber to zero decimal spaces, in the following line it seems to keep the decimal spaces:
NSNumber holidayNightCount = [NSNumber numberWithDouble:sHolidayDuration.value];
Typically casting to int truncates. For example, 3.4 becomes 3 (as is desired), but 3.9 becomes 3 also. If this happens, add 0.5 before casting
int myInt = (int)(sHolidayDuration.value + 0.5);
Here's a bit of a long winded approach
float test = 1.9;
NSNumberFormatter *formatter = [[NSNumberFormatter alloc] init];
[formatter setRoundingMode:NSNumberFormatterRoundHalfUp];
[formatter setMaximumFractionDigits:0];
NSLog(#"%#",[formatter stringFromNumber:[NSNumber numberWithFloat:test]]);
[formatter release];
If you only need an integer why not just use an int
int holidayNightCount = (int)sHolidayDuration.value;
By definition an int has no decimal places
If you need to use NSNumber, you could just cast the Double to Int and then use the int to create your NSNumber.
int myInt = (int)sHolidayDuration.value;
NSNumber holidayNightCount = [NSNumber numberWithInt:myInt];
you can also do the following: int roundedRating = (int)round(rating.floatValue);
Floor the number using the old C function floor() and then you can create an NSInteger which is more appropriate, see:
https://developer.apple.com/library/mac/documentation/Darwin/Reference/ManPages/man3/floor.3.html ....
NSInteger holidayNightCount = [NSNumber numberWithInteger:floor(sHolidayDuration.value)].integerValue;
Further information on the topic here: http://eureka.ykyuen.info/2010/07/19/objective-c-rounding-float-numbers/
Or you could use NSDecimalNumber features for rounding numbers.