Input type currency format with comma and decimal place 2

佐手、 提交于 2020-06-26 06:55:08

问题


I just want to ask how to make a JavaScript of currency format of input type text. Is it possible that the numbers will have comma while you type the number? Also, how to make the number fixed with 2 decimal numbers. If I input a 3 decimal placed numbers the last number will round off so it can be 2 decimal.

I have a textbox which accepts numbers only and I want it to automatically convert the numbers into currency format. 1234.556 will be Php 1,234.56. (Php means Philippine peso)

Here's my input type text:

 <input type="text" name='Etxt11' placeholder="Proposed price"  onblur="this.value = 'Php ' + formatNumber(this.value)" />

回答1:


function formatPera(num) {
    var p = num.toFixed(2).split(".");
    return "Php " + p[0].split("").reverse().reduce(function(acc, num, i, orig) {
        return  num + (i && !(i % 3) ? "," : "") + acc;
    }, "") + "." + p[1];
}

var money = 1234.556;
money = formatPera(money);

console.log(money); // Php 1,234.56

Also, credit goes to: https://stackoverflow.com/a/5342097/1978142




回答2:


maybe like this?

var formatNumber = function (val){
    return val.toFixed(2).replace(/\d(?=(\d{3})+\.)/g, '$&,');
}


来源:https://stackoverflow.com/questions/24030813/input-type-currency-format-with-comma-and-decimal-place-2

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!