Adding digit spacing with jQuery

落爺英雄遲暮 提交于 2019-12-12 18:24:37

问题


I would like to inspect a span element and check for its number format and apply digit grouping to it with jquery

It the number has more than 3 digits, that is for >1000, it must do digit grouping, to separate the thousands from the hundreds, and the hundred thousands from the thousands:

eg.

<span>5500000.00</span>

should become

<span>5 500 000.00</span>

Is that possible with jQuery?


回答1:


There are number of formatting plugins for this task. Or use can use regular expression.

function formatPrice(price) {
    return price.reverse().replace(/((?:\d{2})\d)/g, '$1 ').reverse();
}

// Need to extend String prototype for convinience
String.prototype.reverse = function() {
    return this.split('').reverse().join('');
}

Tests:

formatPrice('1234.00')   // "1 234.00"
formatPrice('12345.00')  // "12 345.00"
formatPrice('123456.00') // "123 456.00"

Maybe there is a way to do this without reverting a string?




回答2:


This links might help :

https://code.google.com/p/jquery-numberformatter/

Javascript: Easier way to format numbers?



来源:https://stackoverflow.com/questions/16060016/adding-digit-spacing-with-jquery

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