Reputation: 81
..so only 3 digit numbers afer "."..
float a = 0.9876543
I would like to have 0.987 only in memory because of transmitting the number over bluetooth..
I'm using iphone SDK..
thank you... :)
Upvotes: 0
Views: 648
Reputation: 426
You have three answers :
the apple way :
float a = 0.9876543;
NSNumber *number = [NSNumber numberWithFloat: a];
NSNumberFormatter *formatter = [NSNumberFormatter new];
[formatter setMaximumFractionDigits:3];
NSLog(@"%@", [formatter stringFromNumber: number]);
[formatter release], formatter = nil;
the Nerd C way :
float a = 0.9876543;
a = roundf(a*1000)*.001f; // or floatf() if you want truncate and not round number
the apple trick :
float a = 0.9876543;
NSString* tmp = [NSString stringWithFormat:@"%.3f",a];
a = [tmp floatValue];
Good luck
Upvotes: 1
Reputation: 17014
A single precision float takes up the same amount of storage whether you're storing an "easy" number like 1.0 or a "complicated" number like 1.23456789. (Likewise for double precision floats -- they're all the same size as each other, although obviously they take more storage space than single precision floats.)
Any network protocol/transport such a Bluetooth involves overheads in just making the thing work, such as headers etc. These overheads mean that the amount of storage you're wanting to save probably just isn't worth the bother - you're talking about shaving a few bytes off a communication which probably a good few multiples bigger than your potential saving anyway.
A more realistic optimization might be to collect some readings and then transmit them all at once, e.g. 32 at once. That makes your "real information" to "protocol overhead" ratio higher.
Here's some advice about optimization you should be aware of:
http://c2.com/cgi/wiki?PrematureOptimization
Don't optimize too early!
Upvotes: 6
Reputation: 10394
Are you trying to print the number? Anyway, I'm not sure if this is what you're looking for:
float a = 0.9876543;
NSNumber *number = [NSNumber numberWithFloat: a];
NSNumberFormatter *formatter = [NSNumberFormatter new];
[formatter setMaximumFractionDigits:3];
NSLog(@"%@", [formatter stringFromNumber: number]);
Upvotes: 0