Convert cents value in this INTO WORDS conversion JavaScript

gwbalxhn  于 12个月前  发布在  Java
关注(0)|答案(3)|浏览(74)

我有一个代码,将数值转换为文字。我只是想增加美分的话,如果用户输入的金额有一美分的价值。
例如,如果我有一笔1000.88美元的金额,那么其价值将为壹仟比索零八八美分整

**更新:**代码被编辑为将整数值和美分值分开,剩下的就是美分到文字的转换。

FIDDLE

var NUMBER2TEXT = {
        ones: ['', 'ONE', 'TWO', 'THREE', 'FOUR', 'FIVE', 'SIX', 'SEVEN', 'EIGHT', 'NINE', 'TEN', 'ELEVEN', 'TWELVE', 'THIRTEEN', 'FOURTEEN', 'FIFTEEN', 'SIXTEEN', 'SEVENTEEN', 'EIGHTEEN', 'NINETEEN'],
        tens: ['', '', 'TWENTY', 'THIRTY', 'FOURTY', 'FIFTY', 'SIXTY', 'SEVENTY', 'EIGHTY', 'NINETY'],
        sep: ['', ' THOUSAND ', ' MILLION ', ' BILLION ', ' TRILLION ', ' QUADRILLION ', ' QUINTILLION ', ' SEXTILLION ']
        };

        (function( ones, tens, sep ) {

        var input = document.getElementById( 'totalamountpaid' ),
        output = document.getElementById('words');

        input.onkeyup = function() {
        var val = this.value,
        arr = [],
        str = '',
        i = 0;

        if ( val.length === 0 ) {
        output.textContent = 'No amount paid';
        return;  
        }

        val = val.replace(/,/g,'');
        if ( isNaN( val ) ) {
        output.textContent = 'Invalid input.';
        return;   
        }

       val = val.toString();
       var valArray = val.split('\.', 2); //splits val into two seperate integers, whole numbers and decimals, in an array.   
       val = valArray[0]; //this is the whole number
       var val2 = valArray[1]; //this should be the decimals

        if(val2 != null && val2 != ''){
        //convert the decimals here
        var str2 = 'AND TWENTY CENTS';
        }else{
        var str2 = '';
        }

        while ( val ) {
        arr.push( val % 1000 );
        val = parseInt( val / 1000, 10 );   
        }

        while ( arr.length ) {
        str = (function( a ) {
        var x = Math.floor( a / 100 ),
        y = Math.floor( a / 10 ) % 10,
        z = a % 10;

        return ( x > 0 ? ones[x] + ' HUNDRED ' : '' ) +                 
        ( y >= 2 ? tens[y] + ' ' + ones[z] : ones[10*y + z] ); 
        })( arr.shift() ) + sep[i++] + str;                     
        }


        output.textContent = str + ' ' + str2 + ' PESOS ONLY';       
        };

        })( NUMBER2TEXT.ones, NUMBER2TEXT.tens, NUMBER2TEXT.sep );

字符串

bzzcjhmw

bzzcjhmw1#

对不起,等待,由于某种原因,这一行正在攻击我的代码。

val = parseInt( val.replace(/,/g,''), 10 );

字符串
我把它改成:

val = val.replace(/,/g,'');


它似乎有同样的功能,同时允许我做我的事情。下面是代码。我使用正则表达式来测试val中的一个周期。(if语句),然后将瓦尔拆分为句号之前和之后的内容。split函数中的2应该只允许2个字符串从其中出来,这意味着10.20将变成'10'和'20',而1.2.3将变成'1'和'2',并丢弃3。数组从0开始,因此valArray[0]是数组中的第一个字符串,valArray[1]是第二个。

val = val.toString();
var valArray = val.split('\.', 2); //splits val into two seperate integers, whole numbers and decimals, in an array.   
val = valArray[0]; //this is the whole number
var val2 = valArray[1]; //this should be the decimals

if(val2 != null && val2 != ''){
//convert the decimals here
var str2 = 'TWENTY CENTS';
}
else{
var str2 = '';
}


更新:FIDDLE

093gszye

093gszye2#

这里是一个完整的版本使用美元和美分

const num2text = {
  ones: ['', 'ONE', 'TWO', 'THREE', 'FOUR', 'FIVE', 'SIX', 'SEVEN', 'EIGHT', 'NINE', 'TEN', 'ELEVEN', 'TWELVE', 'THIRTEEN', 'FOURTEEN', 'FIFTEEN', 'SIXTEEN', 'SEVENTEEN', 'EIGHTEEN', 'NINETEEN'],
  tens: ['', '', 'TWENTY', 'THIRTY', 'FOURTH', 'FIFTY', 'SIXTY', 'SEVENTY', 'EIGHTY', 'NINETY'],
  sep: ['', ' THOUSAND ', ' MILLION ', ' BILLION ', ' TRILLION ', ' QUADRILLION ', ' QUINTILLION ', ' SEXTILLION ']
};
const convert = function(val) {
  if (val.length === 0) {
    return '';
  }

  val = val.replace(/,/g, '');
  if (isNaN(val)) {
    return 'Invalid input.';
  }


  let [val1, val2] = val.split(".")
  let str2 = "";
  if (val2 != null && val2 != '') {
    //convert the decimals here
    var digits = (val2+"0").slice(0,2).split("");
    str2 = num2text.tens[+digits[0]] + " " + num2text.ones[+digits[1]]
  }
  let arr = [];
  while (val1) {
    arr.push(val1 % 1000);
    val1 = parseInt(val1 / 1000, 10);
  }
  let i = 0;
  let str = "";
  while (arr.length) {
    str = (function(a) {
      var x = Math.floor(a / 100),
        y = Math.floor(a / 10) % 10,
        z = a % 10;

      return (x > 0 ? num2text.ones[x] + ' HUNDRED ' : '') +
        (y >= 2 ? num2text.tens[y] + ' ' + num2text.ones[z] : num2text.ones[10 * y + z]);
    })(arr.shift()) + num2text.sep[i++] + str;
  }

  return str +
    ' DOLLARS ' +
    (str2 ? ' AND ' + str2 + ' CENTS' : '') +
    ' ONLY';
};


window.addEventListener("load", function() {
  document.getElementById("totalamountpaid").addEventListener("input", function() {
    document.getElementById("words").innerHTML = convert(this.value)
  });
});

个字符

1cklez4t

1cklez4t3#

这是对@mplungjan的改进

const num2text = {
ones: [
    '',
    'ONE',
    'TWO',
    'THREE',
    'FOUR',
    'FIVE',
    'SIX',
    'SEVEN',
    'EIGHT',
    'NINE',
    'TEN',
    'ELEVEN',
    'TWELVE',
    'THIRTEEN',
    'FOURTEEN',
    'FIFTEEN',
    'SIXTEEN',
    'SEVENTEEN',
    'EIGHTEEN',
    'NINETEEN',
],
tens: [
    '',
    '',
    'TWENTY',
    'THIRTY',
    'FOURTY',
    'FIFTY',
    'SIXTY',
    'SEVENTY',
    'EIGHTY',
    'NINETY',
],
sep: [
    '',
    ' THOUSAND ',
    ' MILLION ',
    ' BILLION ',
    ' TRILLION ',
    ' QUADRILLION ',
    ' QUINTILLION ',
    ' SEXTILLION ',
],
};

export const convertAmountToWords = function (
amount: any,
currency?: string,
smallestUnit?: string
) {
if (!amount) return '';

if (amount.length === 0) {
    return '';
}

amount = amount.replace(/,/g, '');

if (isNaN(amount)) {
    return 'Invalid input.';
}

// eslint-disable-next-line prefer-const
let [val1, val2] = amount.split('.');
let str2 = '';
if (val2 != null && val2 != '') {
    //convert the decimals here
    const digits = (val2 + '0').slice(0, 2).split('');
    str2 = convertAmountToWords(digits.join(''));
}
const arr = [];
while (val1) {
    arr.push(val1 % 1000);
    val1 = parseInt(String(val1 / 1000), 10);
}
let i = 0;
let str = '';
while (arr.length) {
    str =
        (function (a) {
            if (!a) return '';

            const x = Math.floor(a / 100),
                y = Math.floor(a / 10) % 10,
                z = a % 10;

            return (
                (x > 0 ? num2text.ones[x] + ' HUNDRED AND ' : '') +
                (y >= 2
                    ? num2text.tens[y] + ' ' + num2text.ones[z]
                    : num2text.ones[10 * y + z])
            );
        })(arr.shift()) +
        num2text.sep[i++] +
        str;
}

if (!currency) return str;

return (
    str +
    ` ${currency}` +
    (str2 ? ', ' + str2 + ` ${smallestUnit}` : '')
).toLowerCase();
};

字符串

相关问题