When I calculate with numbers in my App, there are no decimals in my output!
this is the code I am using:
int Vijfhonderdmeter = [_VijfHonderd.text intValue];
int vijftienhonderdmeter = [_vijftienhonderd.text intValue];
int vijfdeeldrie = vijftienhonderdmeter / 3;
int puntentotaal = Vijfhonderdmeter + vijfdeeldrie;
_PuntenTotaal.text = [NSString stringWithFormat:#"%d",puntentotaal];
The real output should be 87,18667, but my _Puntentotaal label only shows 87.
Has anyone got a solution?
By the way:
(_VijfHonderd.text intValue = 44.05).
(_vijftienhonderd.text intValue = 129.41).
Thank you for your time and help :)
3 problems:
1) You are using integer division with integer value. If you want floating point numbers you need to floating point values and do floating point division:
double Vijfhonderdmeter = [_VijfHonderd.text doubleValue];
double vijftienhonderdmeter = [_vijftienhonderd.text doubleValue];
double vijfdeeldrie = vijftienhonderdmeter / 3.0;
2) You are formatting the result using %d. Use %f with the double values.
3) Use NSNumberFormatter, not stringWithFormat: to format the numbers. This will ensure they look correct for all users based on their locale.
Your code will always return a non decimal value as you are operating with int datatype.
int Vijfhonderdmeter = [_VijfHonderd.text intValue]; here you are getting a non decimal value & later also you are operating it with other non-decimal values. To get decimal values, you should use `double` or `float` datatype.
For now,try this:
float Vijfhonderdmeter = [_VijfHonderd.text floatValue];
float vijftienhonderdmeter = [_vijftienhonderd.text floatValue];
float vijfdeeldrie = vijftienhonderdmeter / 3;
float puntentotaal = Vijfhonderdmeter + vijfdeeldrie;
_PuntenTotaal.text = [NSString stringWithFormat:#"%f",puntentotaal];
Refer this link for more knowledge about premitive datatypes in objective-C
Related
I am learning Objective-C and iOS development by making a simple tip calculator. However, the issue I am having is when I try to calculate the tip. This is simple math (tip percent / total bill) * 100. This is exactly what I am doing, but I am really confused as to why my output is wrong.
This is the method in my ViewController.m file that is giving me issues
- (IBAction)doCalculate:(id)sender {
NSInteger totalBillAmount = self.inputTotalBill.text.intValue;
NSLog(#"input total bill: %i", totalBillAmount);
NSInteger tipPercent = self.inputTip.text.intValue;
NSLog(#"input tip percent: %i", tipPercent);
NSInteger tipAmount = (tipPercent / totalBillAmount) * 100;
NSLog(#"tip amount: %i", tipAmount);
NSInteger billAmount = totalBillAmount + tipAmount;
NSLog(#"total bill: %i", billAmount);
// Set labels accordingly
self.labelTipAmount.text = [NSString stringWithFormat:#"%i", tipAmount];
self.labelBillAmount.text = [NSString stringWithFormat:#"%i", billAmount];
}
And this is my output:
2016-02-28 01:39:36.283 conversion[1533:58347] input total bill: 100
2016-02-28 01:39:36.285 conversion[1533:58347] input tip percent: 15
2016-02-28 01:39:36.285 conversion[1533:58347] tip amount: 0
2016-02-28 01:39:36.285 conversion[1533:58347] total bill: 100
I am really confused so any help is appreciated, thanks!
Computer numbers does not behave like numbers you learned at school. Integers only use integer arithmetic, and then integer division (look on the web).
4/100 (as an integer division) gives 0 (remember Euclidian division?) If you want to make more natural computations, use floats or doubles (but they will surprise you even more later!).
When you divide two NSIntegers, the result is one NSInteger. If that fraction is <1 and >0 then the output is 0. Using NSInteger might not be the best option here if you want it to be simple.
NSInteger tipAmount = (tipPercent * totalBillAmount) / 100;
NSLog(#"tip amount: %i", tipAmount); // tip amount: 0
If you used a float, it would be a whole lot cleaner:
float tipAmount = (tipPercent * totalBillAmount) / 100;
NSLog(#"tip amount: $%.02f", tipAmount); // tip amount: $15.00
However, using floats for currency can be very bad. So, it would be a more sage decision to use NSInteger to keep track of the smallest unit of currency instead. For the USD this is $0.001, or one tenth of a cent.
This means, when someone enters the bill total, let's say $100.00, you would record that value as 100000.
Then, to calculate 15%, you would multiply the bill by 15 and then divide by 100.
NSInteger tipAmount = (tipPercent * totalBillAmount) / 100;
NSLog(#"tip amount: %i", tipAmount); // tip amount: 15000
To show the user again, I would use a method like the following to convert from tenth cent units to a formatted string for dollars:
- (NSString *)tenthCentToDollarString:(NSInteger)tenthCents {
if (tenthCents >= 0) {
NSInteger roundedCents = (tenthCents + 5) / 10;
if (roundedCents < 10) {
return [NSString stringWithFormat:#"$0.0%zd", roundedCents];
}
if (roundedCents < 100) {
return [NSString stringWithFormat:#"$0.%zd", roundedCents];
}
NSInteger cents = roundedCents % 100;
NSInteger dollars = roundedCents / 100;
if (cents < 10) {
return [NSString stringWithFormat:#"$%zd.0%zd", dollars, cents];
}
return [NSString stringWithFormat:#"$%zd.%zd", dollars, cents];
}
// Dollar amount is negative
NSInteger positiveTenthCents = ABS(tenthCents);
NSString *dollarString = [self tenthCentToDollarString:positiveTenthCents];
return [NSString stringWithFormat:#"-%#", dollarString];
}
A couple issues: You should be doing tipAmount = (tipPercent / 100) * totalBillAmount and cast to doubles because NSInts can't do fractions.
I am facing problem with the objective c code to convert decimal to binary. When I enter small values it shows me the output.
For e.g. 12 -> 1010
But when I enters large numbers, it shows me the output as "10..." (includes dots in the output)
Please help me.
My program is as follows:
NSUInteger x = [newDec integerValue];
//int y[30];
int i=0;
int m =1;
while (x != 0) {
int mod = x % 2;
x /= 2;
i = i + mod * m;
m = m * 10;
string = [NSString stringWithFormat:#"%d", i];
}
There are two problems with your code.
1) Your label size is perhaps not able to accommodate your string. So check the length of it.
2) Your code will not support the conversion if value of x is large. The reason is that int has limited capacity. Check this question regarding memory size of in-built variable. So, consider making your string mutable and add 0s or 1s in it. I am attaching my snippet of code.
NSMutableString *string = [[NSMutableString alloc] init];
while (x != 0) {
int mod = x % 2;
x /= 2;
[string insertString:[NSString stringWithFormat:#"%d", mod] atIndex:0];
}
NSLog(#"String = %#", string);
The following produces the below error:
int calc_ranks(ranks)
{
double multiplier = .5;
return multiplier * ranks;
}
The return type double is not a int, as defined by the method calc_ranks. How do I round/cast to an int?
Round it using the round() method:
int calc_ranks(ranks) {
double multiplier = .5;
return (multiplier * ranks).round();
}
You can use any of the following.
double d = 20.5;
int i = d.toInt(); // i = 20
int i = d.round(); // i = 21
int i = d.ceil(); // i = 21
int i = d.floor(); // i = 20
You can simply use toInt() to convert a num to an int.
int calc_ranks(ranks)
{
double multiplier = .5;
return (multiplier * ranks).toInt();
}
Note that to do exactly the same thing you can use the Truncating division operator :
int calc_ranks(ranks) => ranks ~/ 2;
I see a lot of answers, but with less description. Hope my answer will add some value.
Lets initalize the variable, and see how it will change with different methods.
double x = 8.5;
toInt()
It truncates the decimal value.
int a = x.toInt();
print(a); // 8
truncate()
It also truncates the decimal value.
int b = x.truncate();
print(b); // 8
round()
It returns the closest integer. It uses half up rounding mode.
int c = x.round();
print(c); // 9
ceil()
It returns the closest integer greater than the value.
int c = x.ceil();
print(c); // 9
floor()
It returns the closest integer smaller than the value.
int c = x.floor();
print(c); // 8
I looked at the answers above and added some more answers to make it a little easier to understand.
double value = 10.5;
Using toInt()
void main(){
double value = 10.5;
var y = value.toInt();
print(y);
print(y.runtimeType);
}
Using round()
The round() method returns the closest integer to the double.
void main(){
double value = 9.6;
var b = value.round();
print(b);
print(b.runtimeType);
}
Using ceil()
The ceil() method returns the smallest integer that is equal or greater than the given double.
void main(){
double value = 9.5;
var d = value.ceil();
print(d);
print(d.runtimeType);
}
Using floor()
The floor() method returns the greatest integer not greater than the given double.
void main(){
double value = 10.9;
var j = value.floor();
print(j);
print(j.runtimeType);
}
Conclusion
We’ve gone through 4 different techniques to convert a double to an integer in Dart and Flutter. You can choose from the method that fits your use case to solve your problem. Flutter is awesome and provides a lot of amazing features.
To convert double to int just this:
division
double01 ~/ double02
PS: The operator x ~/ y is more efficient than (x / y).toInt().
Multiplication, addition and subtraction
(double01 * double02).toInt
(double01 + double02).toInt
(double01 - double02).toInt
Its easy,
(20.8).round()
For String,
double.tryParse(20.8).round()
from string to int ->
if you string in int format like '10'
then use ---->
int.parse(value)
but if string in double format like '10.6'
then use like this ---->
double.parse(value).toInt()
convert double to int
doubleValue.toInt()
Try this!
int calc_ranks(ranks)
{
double multiplier = .5;
return (multiplier * ranks).truncate();
}
class CurrencyUtils{
static int doubletoint(double doublee) {
double multiplier = .5;
return (multiplier * doublee).round();
}
}
----------------------
CustomText( CurrencyUtils.doubletoint(
double.parse(projPageListss[0].budget.toString())
).toString(),
fontSize: 20,
color: Colors.white,
font: Font.QuicksandSemiBold,
),
There's another alternative, you can first cast the double to 'num' datatype and then convert to int using toInt().
double multiplier = .5;
return ((multiplier * ranks) as num).toInt();
The num type is an inherited data type of the int and double types.
You can cast both int and double to num, then cast it again to whatever you want
(double -> use toDouble(), int -> use toInt())
This question already has answers here:
How do I restrict a float value to only two places after the decimal point in C?
(17 answers)
Closed 9 years ago.
Let me know how to round decimal for 2 decimal places in Objective-C.
I would like to do like this.
(all of numbers following sentence is float value)
• round
10.118 => 10.12
10.114 => 10.11
• ceil
10.118 => 10.12
• floor
10.114 => 10.11
Thanks for checking my question.
If you actually need the number to be rounded, and not just when presenting it:
float roundToN(float num, int decimals)
{
int tenpow = 1;
for (; decimals; tenpow *= 10, decimals--);
return round(tenpow * num) / tenpow;
}
Or always to two decimal places:
float roundToTwo(float num)
{
return round(100 * num) / 100;
}
You can use the below code to format it to two decimal places
NSNumberFormatter *formatter = [[NSNumberFormatter alloc] init];
formatter.numberStyle = NSNumberFormatterDecimalStyle;
formatter.setMaximumFractionDigits = 2;
formatter.setRoundingMode = NSNumberFormatterRoundUp;
NSString *numberString = [formatter stringFromNumber:#(10.358)];
NSLog(#"Result %#",numberString); // Result 10.36
float roundedFloat = (int)(sourceFloat * 100 + 0.5) / 100.0;
the maximum value for an 32-Bit integer is: 2^31-1 = 2147483647.
but just with negative and positive number. because the half of the number is negative.
so the real maximum value is 2^32-1 = 4294967295. but in this case we just use positive numbers.
ok, a normal int is both negative and positive number.
i want to use just positive number because i want the maximum value to be: 4294967295.
i'm going to use
"unsigned int"
instead of
"int"
but this will not work!
the maximum value is still 2147483647.
here is the code for a simple random number generator:
-(Action for my button) {
unsigned int minNumber;
unsigned int maxNumber;
unsigned int ranNumber;
minNumber=[self.textFieldFrom.text intValue]; //getting numbers from my textfields
maxNumber=[self.textFieldTo.text intValue]; //Should i use unsigned intValue?
ranNumber=rand()%(maxNumber-minNumber+1)+minNumber;
NSString *str = [NSString stringWithFormat:#"%d", ranNumber];
self.label.text = str;
}
and this will view : 2147483647 as a maximum value.
what's wrong? should i use unsigned intValue when i getting numbers from my textFields?
Jonathan
here you can read about this number. : http://en.wikipedia.org/wiki/2147483647
The problem is intValue which returns a int (not an unsigned int) and is maxed out at 2,147,483,647. If you need larger than INT32_MAX, then use long variables and NSString method longLongValue instead of intValue.
Yes, %d is signed, but if you use %u that will not solve the problem with intValue. Using long long variables and longlongValue method will solve this. For example:
NSString *string = #"2147483650";
unsigned int i = [string intValue];
NSLog(#"i = %u", i); // returns 2147483647
NSUInteger j = [string integerValue];
NSLog(#"j = %u", j); // returns 2147483647
long long k = [string longLongValue];
NSLog(#"k = %lld", k); // returns 2147483650
So, looking at your original code, it might be:
long long minNumber;
long long maxNumber;
long long ranNumber;
minNumber = [self.textFieldFrom.text longLongValue];
maxNumber = [self.textFieldTo.text longLongValue];
ranNumber = arc4random_uniform(maxNumber-minNumber+1) + minNumber;
NSString *str = [NSString stringWithFormat:#"%lld", ranNumber];
self.label.text = str;
%d modifier is parsed as signed integer.