Skip to content Skip to sidebar Skip to footer

Converting A Number In English To Its Digital Value (ignore Decimals)

I want to convert these types of values, '3 million', '24 thousand', '350 thousand', etc. to a number. In either JavaScript(so i can do it client side) or PHP(server side). is ther

Solution 1:

do you want to combine them as well?

function convert(num) {
  function mapGroups(str) {
    if (/million/.test(str)) {
      return str.match(/\d+/)[0] * 1000000;
    }
    if (/thousand/.test(str)) {
      return str.match(/\d+/)[0] * 1000;
    }
    if (/hundred/.test(str)) {
      return str.match(/\d+/)[0] * 100;
    }
    return +str;
  }
  
  return num.match(/(\d+)( ?\w* ?)/g)
            .map(mapGroups)
            .reduce(function(p, c) { return p + c });
}

console.log(convert("3 million 240 thousand 7 hundred 54")) //3240754
console.log(convert("5 millions 7 hundreds 54")) //5000754

it is very basic but you do get a grip.


Solution 2:

There is no miracle solution but the NumberFormatter::parse PHP function may help you solve your issue :

$fmt = numfmt_create('en_US', NumberFormatter::SPELLOUT);
echo numfmt_format($fmt, '1234567');

Will output one million two hundred thirty-four thousand five hundred sixty-seven and

$fmt = numfmt_create('en_US', NumberFormatter::SPELLOUT);
echo numfmt_parse($fmt, 'one million two hundred thirty-four thousand five hundred sixty-seven');

Will output 1234567.

Sadly, this will not work with mixed-type value like "24 thousand" (it needs to be entirely spelled out) but you may throw together a workaround by spelling out actual digits in your string first.


Solution 3:

    $str = str_replace('hundred','00',$str);
    $str = str_replace('thousand','000',$str);
    $str = str_replace('million','000000',$str);
    $str = str_replace('billion','000000000',$str);
$str = str_replace(' ','',$str);

Like that :)


Solution 4:

Assuming:

  1. you have the numeric part ALWAYS written in number format
  2. the unit are consistent and spelled correctly, that is you always have 'million' and not 'millions', or 'milion'
  3. the number syntax is correct (something like 3 million, 24 thousand, ecc)

you could use a map like:

var unitMap = [million:6, thousand:3, '':1] // add as many units as you like

and then convert the string into a number. Here's an idea using javascript and jQuery.

var UNIT_SEPARATOR = ', '; // what separates the number parts (millions from thousands, ecc)
var VALUE_UNIT_SEPARATOR = ' '; // what goes between the value and the unit
var unitMap = {
    billion:9,
    million:6,
    thousand:3,
    '':1
}; // add as many units as you like

$('#convert').click(function () {
    var number = $('#input').val();
    var numberParts = number.split(UNIT_SEPARATOR);
    var convertedNumber = 0;

    for (var i = 0; i < numberParts.length; i++) {
        var splitUnit = numberParts[i].split(' ');
        var value = parseFloat(splitUnit[0]);
        var exp = (splitUnit.length === 1) ? 0 : parseInt(unitMap[splitUnit[1]]);

        var temp = value * Math.pow(10, exp);

        convertedNumber += temp;
    }

    $('#result').text(convertedNumber);
});

Here's the fiddle

NOTE this is a hint. Input should be sanitized and validated before using this. Also this approach is very error-prone, so you should test it carefully before applying it (se the above assumptions).

Hope it helps! ;)


Solution 5:

I enjoy problems like these, here is my take on it in PHP. I wanted to make it as compact as possible, and it is easy to extend if you want to use thousandths or millionths.

I had to add the + 0 to deal with the possibility of a trailing +, which works but I'm not a fan of how it looks. If there comes a need to filter for characters prior to eval(), I'd introduce some regex and just get rid of \+$.

$find_replace = array(
    array('hundred', 'thousand', 'million', 'billion'),
    array('* 1e2 +', '* 1e3 +', '* 1e6 +', '* 1e9 +')
);

function words_to_number($input) {
    global $find_replace;
    $equation = str_replace($find_replace[0], $find_replace[1], $input) . ' + 0';
    $eval_result = eval('$result = ' . $equation . ';');
    return $eval_result === false ? $eval_result : $result;
}

$words = '3 million 240 thousand 7 hundred 54';
$number = words_to_number($words);
echo $words . ($number === false ? ' error!' : " == $number") . "\n";
// 3 million 240 thousand 7 hundred 54 == 3240754

$words = '5 thousand';
$number = words_to_number($words);
echo $words . ($number === false ? ' error!' : " == $number") . "\n";
// 5 thousand == 5000

Post a Comment for "Converting A Number In English To Its Digital Value (ignore Decimals)"