Javascript: Easier way to format numbers?(Javascript:格式化数字的更简单方法?)
问题描述
我正在尝试格式化页面上的各种数字.这些数字代表价格、价格变化或百分比.我知道 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:格式化数字的更简单方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:Javascript:格式化数字的更简单方法?
基础教程推荐
- 动态更新多个选择框 2022-01-01
- Karma-Jasmine:如何正确监视 Modal? 2022-01-01
- 当用户滚动离开时如何暂停 youtube 嵌入 2022-01-01
- 我什么时候应该在导入时使用方括号 2022-01-01
- 有没有办法使用OpenLayers更改OpenStreetMap中某些要素 2022-09-06
- 在 JS 中获取客户端时区(不是 GMT 偏移量) 2022-01-01
- 悬停时滑动输入并停留几秒钟 2022-01-01
- 响应更改 div 大小保持纵横比 2022-01-01
- 在for循环中使用setTimeout 2022-01-01
- 角度Apollo设置WatchQuery结果为可用变量 2022-01-01