Skip to content

Instantly share code, notes, and snippets.

@thomasjao
Last active August 29, 2015 13:56
Show Gist options
  • Save thomasjao/9088011 to your computer and use it in GitHub Desktop.
Save thomasjao/9088011 to your computer and use it in GitHub Desktop.
strip commas off from formatted digits to real number or integer
// NOTE: ensure numString contains only validate value, e.g. only digits, comma and period allowed
function toReal( numString ) {
if ( numString.contains('.') ) { // deem as real number with period within, regardless if comma exists
return parseFloat(numString.replace(/,/g, ''));
} else {
return parseInt( numSring ); // deem as integer, without period
}
}
@thomasjao
Copy link
Author

Convert digit strings with comma to number -- 轉換具撇節號的數字成為真正的數字

example

var a = '123,456,789.32';
var b = '123456789.32';
var c = '123';

var output1 = toReal( a );          // return 123456789.32
var output2 = toReal( b );          // return 123456789.32
var output3 = toReal( c );            // return 123

Data from outer source like excel CVS output may contains digits with comma, which in JavaScript will be deemed as a string. Use stripComma() to convert it into real number.

由外部轉來的資料 (例如 Excel 的 CVS 輸出),數字欄位中有時含已格式化的三位敝節符號,在 JavaScript 處理時會將它當作字串處理。使用 stripComma() 將這些資料轉成真正的數字。

注意: 使用 stripComma() 時需先確定資料祇含數字、逗點及句點

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment