NSString - Truncate everything after decimal point in a double - iphone

I have a double that I need only the value of everything before the decimal point.
Currently I am using
NSString *level = [NSString stringWithFormat:#"%.1f",doubleLevel];
but when given a value of 9.96, this returns "10". So it is rounding. I need it to return only the "9". (note - when the value is 9.95, it correctly returns the "9" value.)
Any suggestions?
Thank You.

Simply assign the float/double value to a int value.
int intValue = doubleLevel;

Cast that baby as an int.
int castedDouble = doubleLevel;
Anything after the . in the double will be truncated.
9.1239809384 --> 9
123.90454980 --> 123
No rounding, simple truncation.

If you want to keep it as a float:
CGFloat f = 9.99;
f = floorf(f);
there are quite a variety of floor and round implementations.
they have been around since UN*X, and are actually part of those low-level libraries, be they BSD, Posix, or some other variety - you should make yourself familiar with them.
there are different versions for different "depths" of floating point variables.

NSString *level = [NSString stringWithFormat:#"%d",doubleLevel];

Related

Double being displayed with unnecessary zeros after decimal

In my calculator app, I am trying to display a "double" value in a UILabel. However, the value always has more zeros than it needs. For example, 64 is displayed as 64.000000, 4.23 is displayed as 4.230000, etc.
How can I make it display only as many decimal places as fits?
vector<Token> postfix; // create empty postfix vector
infixToPostfix(infix, postfix); // call inToPost to fill up postfix vector from infix vector
answer = postFixEvaluate(postfix); // evaluate expression
expString.clear();
expNSString = [NSString stringWithFormat:#"%f", answer]; // convert "answer" to NSString
displayScreen.text = expNSString; // display answer in UIlabel "displayScreen"
As mentioned in the [NSString stringWithFormat:] class reference:
Parameters
format A format string. See “Formatting String Objects” for
examples of how to use this method, and “String Format Specifiers” for
a list of format specifiers. This value must not be nil.
and following the first link, one of the first examples is:
NSString *string1 = [NSString stringWithFormat:#"A string: %#, a float: %1.2f",
#"string", 31415.9265]; // ^
// string1 is "A string: string, a float: 31415.93"
You need to learn to think for yourself. Read the documentation!
This question is a little old, but did you try %g? This will produce scientific notation in some cases:
64-bit floating-point number (double), printed in the style of %e if the exponent is less than –4 or greater than or equal to the precision, in the style of %f otherwise.
But, as it says, you can control this to some extent using the precision field: if your numbers are large, you will need to increase the precision to avoid scientific notation. If your numbers are small, then I think there is nothing you can do about it when using %g.
I get this output:
64.0 -> "64"
64.1 -> "64.1"
64.15555 -> "64.1556" // default precision is 6

formatting NSDecimalNumber issue

I'm trying to create NSDecimalNumber with simply format like: 123.00 with two fractional digits after dot, always. I tried use the NSFormatter and many other ways like converting float from string and creating then NSDecimalNumber from this string, but it's not working.
The problem is that I need only NSDecimalNumber in this format, not NSString or any other.
Thanks for any advice,
Paul
You may get idea from this.
float num = 123.1254546;
NSString *str = [NSString stringWithFormat:#"%.2f",num];
NSLog(#"%.2f %#",num,str);
I think you simply need to do Type Casting operation for Two times as bellow
float value = 123.562;
int myDigit = value;
it gives value 123 in myDigit variable
NSLog(#"MyDigit in Decimal = %d",myDigit);
Output is MyDigit in Decimal = 123
now if you want output like 123.000 then simply write as bellow
float valueWithZiro = myDigit;
NSLog(#"MyDigit with 000 == %3f",valueWithZiro);
Output is MyDigit in Decimal = 123.000
NSDecimalNumber, like NSNumber, cannot contain formatting information. The object structure simply doesn't support it. It represents a number, not the way the number is displayed.
You can convert it to a formatted NSString (which you say you don't want). But you can't do what you're asking.
You convert it to a formatted NSString using an NSNumberFormatter. It's the object that allows you to specify the decimal and thousands separators, number of decimal places to display, the currency symbol, etc.
Maybe you were looking to store a NSNumberDecimal with just two digits after the fraction?
If so NSDecimalNumberBehaviors is your friend.
I had a similar need and used the following:
self.decimalHandlingBehaviorForApp = [NSDecimalNumberHandler
decimalNumberHandlerWithRoundingMode:NSRoundUp
scale:2 raiseOnExactness:NO
raiseOnOverflow:NO raiseOnUnderflow:NO
raiseOnDivideByZero:YES];
Edit: added example of using it
// update the taxable total first
self.cartTaxableTotal = [self.cartTaxableTotal decimalNumberByAdding:itemAdded.priceOfItem
withBehavior:self.decimalHandlingBehaviorForApp];

Removing characters after the decimal point for a double

How can I remove the all the characters after the decimal point.
Instead of 7.3456, I would just like 7.
This is what I do to get the number so far with decimal places.
[NSString stringWithFormat:#" %f : %f",(audioPlayer.currentTime),(audioPlayer.duration) ];
Many Thanks,
-Code
You can specify what you want using format string :
[NSString stringWithFormat:#" %.0f : %.0f", (audioPlayer.currentTime),
(audioPlayer.duration)];
If you want this for display, use an NSNumberFormatter:
double sevenpointthreefourfivesix = 7.3456;
NSNumberFormatter * formatter = [[NSNumberFormatter alloc] init];
[formatter setMaximumFractionDigits:0];
NSLog(#"%#", [formatter stringFromNumber:[NSNumber numberWithDouble:sevenpointthreefourfivesix]]);
2011-12-20 20:19:48.813 NoDecimal[55110:903] 7
If you want a value without the fractional part, use round(). If you want the closest integer value not greater than the original value, use floor().
floorf() is the function you're looking for.
you are after
[NSString stringWithFormat:#" %.00f : %.00f",(audioPlayer.currentTime),(audioPlayer.duration) ];
When formatting float you can tell the precision by the number before the f
Cast to int:
[NSString stringWithFormat:#" %i : %i",(int)(audioPlayer.currentTime),(int)(audioPlayer.duration) ];
Casting like this always rounds down (eg: just removes everything after the decimal place). This is what you asked for.
In the case of rounding to the NEAREST whole number you want to add 0.5 to the number
[NSString stringWithFormat:#" %i : %i",(int)(audioPlayer.currentTime+0.5f),(int)(audioPlayer.duration+0.5f) ];
This will round to the nearest whole number. eg: 1.2 becomes 1.7 and casting to int makes 1. 3.6 becomes 4.1 and casting makes 4. :)
Why not just cast the audioPlayer.currentTime to an integer before you use stringWithFormat?
[NSString stringWithFormat:#"%d", (int)(audioPlayer.currentTime)];
All you need to do is type-cast the double to an int, like so: int currentTime_int = (int)audioPlayer.currentTime;.
You can use this same approach for the other variable.
Many of the shorter answers here will work correctly. But if you want your code to be really clear and readable, you might want to explicitly specify your desired conversion from float to int, such as using:
int tmpInt = floorf(myFloat); // or roundf(), etc.
and then separately specifying how you want the integer formated, e.g.
... stringWithFormat:#"%d", tmpInt ... // or #"%+03d", etc.
instead of assuming that an inline cast shows what you want.
You may also use
double newDvalue =floor(dValue);
it will remove all the decimals point
using %.0f for string format will be good also

objective-c converting strings to usable numbers

I have strings that look about like this:
stringA = #"29.88";
stringB = #"2564";
stringC = #"12";
stringD = #"-2";
what is the best way to convert them so they can all be used in the same mathmatical formula?? that includes add, subtract.multiply,divide etc
Probably floatValue (as it appears you want floating-point values), though integerValue may also be of use (both are instance methods of NSString).
[stringA doubleValue]
These are all wrong, because they don't handle errors well. You really want an NSNumberFormatter.
If you have the string #"abc" and try to use intValue or floatValue on it, you'll get 0.0, which is obviously incorrect. If you parse it with an NSNumberFormatter, you'll get nil, which is very easy to distinguish from an NSNumber (which is what would be returned if it was able to parse a number).
Assuming that you have NSString variables.
NSString *stringA = #"29.88";
NSString *stringB = #"2564";
NSString *stringC = #"12";
NSString *stringD = #"-2";
suppose, you want to convert a string value to float value, use following statement.
float x=[stringA floatValue];
suppose, you want to convert a string value to integer value, use following statement.
NSInteger y = [stringC intValue];
Hope, it helps to you.

Secure and valid way for converting a "float integer" into a natural integer?

I have a CGFloat that contains only "integers", in the meaning that it actually wants to represent integers only but due to float inprecision it may happen that it internally has a 23.00000000000000000000000142 or something like that. I try to feed an NSDecimalNumber with clean input, so I need to make sure this is truly a naked integer with no dirt. Well, I think this is a good way, but maybe I am wrong:
NSInteger *intVal = floatVal;
That would just get rid of those fragmental parts at the end of the tale, right? Or is there a more secure way to convert it into a true integer?
If you just want to take the integer part of a float then I believe you can just do the following:
CGFloat myfloat = 23.0000000000142f;
int myInt = (int) myfloat;