[英]Number to Decimal Format with Four Decimal extra
使用Angularjs 1.xx
var transformedInput = text.replace(/[^0-9.]/g, '')
.replace(/\B(?=(\d{3})+(?!\d))/g, ",");
if(transformedInput!="")
transformedInput="$"+transformedInput;
輸入= 123456789,輸出= $ 123,456,789
但是我需要以下輸出:
輸入= 20.56,輸出= $ 20.5600
輸入= 20,輸出= $ 20.0000
輸入= 20.567,輸出= $ 20.5670
不使用過濾器。
使用parseFloat將字符串轉換為float,然后使用toFixed(4)
var text = "20"; var transformedInput = text.replace(/[^0-9.]/g, '') .replace(/\\B(?=(\\d{3})+(?!\\d))/g, ","); if(transformedInput!="") transformedInput="$"+parseFloat(transformedInput).toFixed(4); console.log(transformedInput);
使用角度貨幣過濾器
<span data-ng-bind="'123456789'| currency : '$' : 4 "></span>
希望此實現對您有用。
var msg = document.getElementById('myInputBox'), btn = document.getElementById('formatButton'); btn.addEventListener('click', getFormattedData); function checkNumeric(str) { return str.replace(/\\,|\\$/g, ''); } Number.prototype.format = function() { return this.toString().replace(/(\\d)(?=(\\d{3})+(?!\\d))/g, "$1,"); }; function getFormattedData() { var num = checkNumeric(msg.value), val = (Number(num).toFixed(4)).toString().split('.'), decimal = ''; if (num.indexOf('.') > -1) { decimal = '.' + val[1]; } msg.value = '$' + Number(val[0]).format() + decimal; }
<input type="text" id='myInputBox' value="" /> <input type="button" id="formatButton" value='Get Output'>
您已經有了內置的Number#toLocaleString
,它正是為此目的而設計的:
var nbs = [20.56, 20, 20.567]; var $s = nbs.map(n => n.toLocaleString('en-US', { style: 'currency', // that's money currency: 'USD', // that's $ // the difficult (?) part // we need to get the length of digits before "." minimumSignificantDigits: ((~~n) + '').length + 4 }) ); console.log($s);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.