0

I am struggling to come up with an algorithm in C++ that converts a number with a decimal point from a base to any other base. I have successfully been able to write a function that converts numbers without decimal points to any desired base.

double  getBase10 (string number, int CurrentBase){
    double converted =0;
    for (int i =0; i < number.length(); i++){
        converted += pow(CurrentBase, -1 * (number.length() - i -1)) * getNumber(number[i]);
    }
    return double converted;
}

This is the function I have so far as requested by Mooing Duck.

Mooing Duck
  • 64,318
  • 19
  • 100
  • 158
  • Can you show the code you have without decimals? I bet it can be trivially expanded for decimals – Mooing Duck Sep 09 '14 at 21:49
  • Unrelated, it makes little sense to "convert a number... from a base..." because values don't have bases. _Numeric representations such as strings_ have bases, but numbers themselves don't have bases. So are you converting from a string-represented-number in one base to a string-represented-number in another? Or just from a value to a string-represented-number? – Mooing Duck Sep 09 '14 at 21:51
  • Whoa, this converts a string-represented-number in a base and converts that to a value. Misleading because nothing in this code has anything to do with base10. – Mooing Duck Sep 09 '14 at 22:05
  • Also is there a reason to not be using `stringstream` or `boost::lexical_cast` or somesuch? – Mooing Duck Sep 09 '14 at 22:07
  • Could you please provide an example of how you could accomplish this task using stringstream? – Alex Clark Sep 09 '14 at 22:12
  • Fair point, stringstream and lexical cast only work with specific bases. There's stuff prexisting somewhere. – Mooing Duck Sep 09 '14 at 22:13
  • I don't understand. I am passing in a number and the base that the number is in. How would stringstream help in this situation? – Alex Clark Sep 09 '14 at 22:20
  • I hadn't thought it through the first time. `stringstream` can only read in base 10 and base 16, no others. So it doesn't help this situation. Neither does `boost::lexical_cast` – Mooing Duck Sep 09 '14 at 22:23
  • Also, this code fails for `getBase10("14",10)`. Get it to work right before you expand it. – Mooing Duck Sep 09 '14 at 22:24
  • It works perfectly fine with any base conversions that is a whole number if you take off the negative exponent in the power function. – Alex Clark Sep 09 '14 at 22:26
  • Skip the decimal point - convert as if it weren't there - but count how many digits were to the right of it (say, `n`). The intermediate result is a whole number (which you say you already know how to do). At the end, simply divide by `pow(base, n)`. In other words, `3.14 == 314 / 10^2`. – Igor Tandetnik Sep 09 '14 at 22:32

0 Answers0