[英]Javascript Convert numbers to different formats or string alternative
更新:
使用javascript或jQuery,如何將數字轉換成不同的變體:
例如:
1000000至...
1,000,000 or 1000K
要么
1000至...
1,000 or 1K
要么
1934年和1234年...
1,934 or -2K (under 2000 but over 1500)
要么
1,234 or 1k+ (over 1000 but under 1500)
可以在函數中完成嗎?
希望這有意義。
C
您可以將方法添加到Number.prototype
,例如:
Number.prototype.addCommas = function () {
var intPart = Math.round(this).toString();
var decimalPart = (this - Math.round(this)).toString();
// Remove the "0." if it exists
if (decimalPart.length > 2) {
decimalPart = decimalPart.substring(2);
} else {
// Otherwise remove it altogether
decimalPart = '';
}
// Work through the digits three at a time
var i = intPart.length - 3;
while (i > 0) {
intPart = intPart.substring(0, i) + ',' + intPart.substring(i);
i = i - 3;
}
return intPart + decimalPart;
};
現在,您可以將其稱為var num = 1000; num.addCommas()
var num = 1000; num.addCommas()
,它將返回"1,000"
。 那只是一個例子,但是您會發現創建的所有函數都將涉及在過程的早期將數字轉換為字符串,然后處理並返回字符串。 (將整數和小數部分分開可能會特別有用,因此您可能希望將其重構為自己的方法。)希望這足以使您入門。
編輯:這是做K事情的方法...這有點簡單:
Number.prototype.k = function () {
// We don't want any thousands processing if the number is less than 1000.
if (this < 1000) {
// edit 2 May 2013: make sure it's a string for consistency
return this.toString();
}
// Round to 100s first so that we can get the decimal point in there
// then divide by 10 for thousands
var thousands = Math.round(this / 100) / 10;
// Now convert it to a string and add the k
return thousands.toString() + 'K';
};
用相同的方式調用它: var num = 2000; num.k()
var num = 2000; num.k()
從理論上講,是的。
正如TimWolla指出的那樣,這需要很多邏輯。
Ruby on Rails提供了一個幫助您用單詞表達時間的助手。 看一下文檔 。 可以在GitHub上找到該代碼的實現,並且可以為您提供一些實現方法的提示。
我同意通過選擇一種格式來降低復雜性的意見。
希望您能對我的回答有所幫助。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.