問題描述
我正在嘗試格式化頁面上的各種數字.這些數字代表價格、價格變化或百分比.我知道 Javascript 具有限制小數位數的功能,但是是否支持其他類型的格式,例如用逗號對數字進行分組,控制是否顯示 +/- 等?到目前為止,這是我所擁有的:
I'm trying to format various numbers on my page. These numbers either represent a price, a change in price, or a percentage. I know Javascript has functions to limit the number of decimal places, but is there any support for other types of formatting, such as grouping numbers with commas, controlling whether or not the +/- is shown, etc? Here's what I have so far:
var FORMATTER = {
price : function(value) { return '$' + value.toFixed(2); },
pricePer : function(value) { return (value * 100).toFixed(2) + '%'; },
priceChg : function(value) { return (value >= 0 ? '+' : '-') + '$' + Math.abs(value).toFixed(2); }
};
它工作正常,但它想在price"格式化程序中添加逗號,您可以看到priceChg"格式化程序中有一個黑客,我嘗試將 +/- 符號移到'$' 符號.
It works OK, but it'd like to add commas to the 'price' formatter, and you can see that there's a hack in the 'priceChg' formatter where I try to move the +/- sign in front of the '$' sign.
基本上,我希望有一些庫可以模擬 Java 的 DecimalFormat 類.
Basically, I'm hoping there is some library out there (jQuery is OK) that emulates Java's DecimalFormat class.
推薦答案
這里有NUMBERFORMATTER jQuery插件,詳情如下:
There's the NUMBERFORMATTER jQuery plugin, details below:
https://code.google.com/p/jquery-numberformatter/一個>
從上面的鏈接:
這個插件是一個 NumberFormatter插入.數字格式可能與任何合作過的人都熟悉服務器端代碼,如 Java 或 PHP 和誰合作過國際化.
This plugin is a NumberFormatter plugin. Number formatting is likely familiar to anyone who's worked with server-side code like Java or PHP and who has worked with internationalization.
將鏈接替換為更直接的鏈接.
Replaced the link with a more direct one.
這篇關于Javascript:格式化數字的更簡單方法?的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!