Posts Tagged ‘decimal’

Decimal to Roman Numeral Conversion

21. May 2009

No Comments »

[code lang="cpp"]#include
#include
using namespace std;

string dec_to_numeral(int x) {
int dec[13] = {1000, 900, 500, 400, 100, 90, 50, 40, 10, 9, 5, 4, 1};
string num[13] = {"M", "CM", "D", "CD", "C", "XC", "L", "XL", "X", "IX", "V", "IV", "I"};
string numeral;

for(int i = 0; i < 13; i++) {
while (x >= dec[i]) {
x -= dec[i];
numeral.append(num[i]);
}
}

return numeral;
}

int main() {
//example
cout << dec_to_numeral(400);

return 0;
}[/code]

Binary to Decimal Conversion

21. May 2009

No Comments »

Converts a binary number to its decimal equivalent. However unlike the bindec function, this will preserve the binary/radix point.

Code
[code]

/**
* Convert a binary number with our without
* a radix point to its decimal equivalent.
*
* @param $binary The binary number to convert.
* @param $output Show the calculations.
* @return The decimal conversion
*/
function bin2dec($binary, $output = false) {
$N = 0;
$o = "";
list ( $rhs, $lhs ) = explode ( ".", $binary );
$rhs = strrev ( $rhs );
for($i = 0; $i < strlen ( $rhs ); $i ++) {
$d = $rhs [$i] * pow ( 2, $i );
$N = $d + $N;
$o = ($d == 0) ? $o : $o . $d . " + ";
}

for($i = 0; $i < strlen ( $lhs ); $i ++) {
$d = $lhs [$i] * pow ( 2, - ($i + 1) );
$N = $d + $N;
$o = ($d == 0) ? $o : $o . $d . " + ";
}

return ($output) ? substr ( $o, 0, - 3 ) . " = " . $N : $N;
}

?> [/code]

Usage
[code]echo bin2dec ( "1011101.1000101", true ); [/code]
Output
[code]1 + 4 + 8 + 16 + 64 + 0.5 + 0.03125 + 0.0078125 = 93.5390625[/code]
Usage
[code]echo bin2dec ( "1011101.1000101"); [/code]
Output
[code]93.5390625[/code]