如果一百万或更多,使用撇号将数字格式化为 1'000,000.00
Format a number as 1'000,000.00 using apostrophe if a million or more
我需要在百万之后用撇号格式化我的金额,在千之后用逗号和小数点用句点。使用 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');
}
我需要在百万之后用撇号格式化我的金额,在千之后用逗号和小数点用句点。使用 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');
}