Adding space between numbers

后端 未结 2 1008
不思量自难忘°
不思量自难忘° 2020-12-02 22:21

I\'m trying to make a number input. I\'ve made so my textbox only accepts numbers via this code:

function isNumber(evt) {
    evt = (evt) ? evt : window.even         


        
2条回答
  •  忘掉有多难
    2020-12-02 22:57

    Easiest way:

    1

    var num = 1234567890,
    result = num.toLocaleString() ;// result will equal to "1 234 567 890"
    

    2

    var num = 1234567.890,
    result = num.toLocaleString() + num.toString().slice(num.toString().indexOf('.')) // will equal to 1 234 567.890
    

    3

    var num = 1234567.890123,
    result = Number(num.toFixed(0)).toLocaleString() + '.' + Number(num.toString().slice(num.toString().indexOf('.')+1)).toLocaleString()
    //will equal to 1 234 567.890 123
    

    4

    If you want ',' instead of ' ':

    var num = 1234567.890123,
    result = Number(num.toFixed(0)).toLocaleString().split(/\s/).join(',') + '.' + Number(num.toString().slice(num.toString().indexOf('.')+1)).toLocaleString()
    //will equal to 1,234,567.890 123
    

    If not working, set the parameter like: "toLocaleString('ru-RU')" parameter "en-EN", will split number by the ',' instead of ' '

提交回复
热议问题