我需要格式化数百万个带撇号的格式,数以千个逗号和小数点的格式。使用javascript。最好的方法是什么?谢谢
一些例子:
987654321 -> 987'654,321.00
87654321 -> 87'654,321.00
7654321 -> 7'654,321.00
654321 -> 654,321.00
54321 -> 54,321.00
4321 -> 4,321.00
321 -> 321.00
21 -> 21.00
1 -> 1.00
我想,此功能可以提供帮助:
function formatNumber( num ) {
// String with formatted number
var totalStr = '';
// Convert number to string
var numStr = num + '';
// Separate number on before point and after
var parts = numStr.split( '.' );
// Save length of rounded number
var numLen = parts[0].length;
// Start iterating numStr chars
for ( var i = 0; i < numLen; i++ ) {
// Position of digit from end of string
var y = numLen - i;
// If y is divided without remainder on 3...
if ( i > 0 && y % 3 == 0 ) {
// add aposrtoph when greater than 6 digit
// or add point when smaller than 6 digit
totalStr += y >= 6 ? '\'' : ',';
}
// Append current position digit to total string
totalStr += parts[0].charAt(i);
}
// Return total formatted string with float part of number (or '.00' when haven't float part)
return totalStr + '.' + ( parts[1] ? parts[1] : '00');
}