I have a problem. I need to get two numbers and add them together in a way that one is the decimal point of the other. For example:
double number1 = 20;
double number2 = 142;
I need to add these numbers together to get 20.142. Is there a way to do this?
Thanks
It’s quite simple. We first determine if
number1is negative, and if so, make it positive and set a boolean flag. Then we just keep dividingnumber2by10.0until it is less than1.0(which means it’s now on the range[0, 1)assuming it’s positive). Then we just add the two numbers together and store it infinalnum, and ifnegativeistrue(YES), negatefinalnum.This solution could have also been solved using base-10 logarithms to determine the amount to divide
number2by, but that most likely will take longer.You could also have solved this by turning those numbers into
const char*orCFString(Objective-C) strings and then concatenate them followed by an interpretation of the resulting string as adouble, but again, this will take longer.There are two caveats to this code:
number1andnumber2must be integers (ifnumber1was, say,1.5andnumber2was25.7,finalnumwould be1.757)number2must be positive