且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

使用 CSS 将数字格式化为货币

更新时间:2023-02-10 11:56:38

货币格式可以用 CSS 和一点 Javascript 来实现,这需要解析数字添加逗号.CSS 类添加了额外的样式,如负数(红色)或货币符号(即 $ 美元符号).方法如下:

The currency format can be achieved with CSS and a bit of Javascript which is needed for the parsing of the number to add the commas. A CSS class adds the additional styling like negative (red) or currency sign (i.e. $ Dollar sign). The approach is a follows:

1) 将值转换为数字(根据语言环境添加逗号)

1) Convert the value to number (adds the commas based on the locale)

Number(value).toLocaleString('en');

2) 添加一个类,判断是负值还是正值(即红色)

2) Add a class to determine if it is negative or positive value (i.e. red color)

.enMoney::before {
    content:"$";
}
.negMoney {
    color:red;
}

使用示例代码和 css 在此处查看更多详细信息:

See more detail here with the sample code and css:

http://www.ozkary.com/2014/04/format-currency-with-javascript-and-css.html