Create function normal number formatting?

蹲街弑〆低调 提交于 2019-12-13 02:12:06

问题


I tried the following code but is doesn't work triggers an error:

val.reverse is not a function

How can I fix it?

Demo: http://jsfiddle.net/9ysZa/

//I want this output: 1,455,000
function num(val){
         var result = val.reverse().join("")
                          .match(/[0-9]{1,3}/g).join(",")
                          .match(/./g).reverse().join("");
    return result     
}
alert(num('1455000'))

回答1:


DEMO

reverse is a method on Array.prototype—it works with arrays. Since val is a string, you'll need to call val.split('') to get it into an array.

function num(val){
         var result = val.split('').reverse().join("")
                          .match(/[0-9]{1,3}/g).join(",")
                          .match(/./g).reverse().join("");
    return result     
}
alert(num('1455000'));

Which alerts the results you're looking for.

EDIT

Based on your comment, it looks like you want to run this on the number 1455000 rather than the string '1455000'. If so, adding a toString call before split() will work (and will work on both strings **and numbers).

Here's an updated fiddle



来源:https://stackoverflow.com/questions/8671672/create-function-normal-number-formatting

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