具有四个十进制额外的十进制格式的数字

时间:2017-07-25 07:34:26

标签: javascript angularjs

使用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

4 个答案:

答案 0 :(得分:0)

不使用过滤器。

使用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);

答案 1 :(得分:0)

  

使用Angular货币过滤器

        <span data-ng-bind="'123456789'| currency : '$' : 4 "></span>

答案 2 :(得分:0)

希望此实施对您有用。

&#13;
&#13;
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;
}
&#13;
<input type="text" id='myInputBox' value="" />
<input type="button" id="formatButton" value='Get Output'>
&#13;
&#13;
&#13;

答案 3 :(得分:0)

您已获得内置的Number#toLocaleString,这正是其中的意思:

&#13;
&#13;
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);
&#13;
&#13;
&#13;