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

Formatting a number as currency using CSS(使用 CSS 将数字格式化为货币)
本文介绍了使用 CSS 将数字格式化为货币的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

只是想知道是否有人知道是否可以仅使用 CSS 将元素的内容格式化为货币.如果可能的话,最好能在 CSS 中显示值,但找不到任何东西,所以我没有屏住呼吸 :)

Just wondering if anyone knows whether it is possible to format the content of an element as currency using only CSS. It would be nice to have how the value is presented in CSS if possible, can't find anything though so I'm not holding my breath :)

<!DOCTYPE html>
<html>
<head>
    <style type="text/css">
        .dollars:before { content:'$'; }
    </style>
</head>
<body>
    Pure CSS: <span class="dollars">25153.3</span>
    <br />
    Ideal format: <span>$25,153.30</span>
</body>
</html>

这个例子是这样的:

纯 CSS:$25153.3

理想格式:$25,153.30

我也知道使用 javascript 相当简单 - http://css-tricks.com/snippets/javascript/format-currency/.

Also I'm aware that it's fairly trivial using javascript - http://css-tricks.com/snippets/javascript/format-currency/.

推荐答案

货币格式可以用 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

这篇关于使用 CSS 将数字格式化为货币的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!

本站部分内容来源互联网,如果有图片或者内容侵犯您的权益请联系我们删除!

相关文档推荐

how to remove this error quot;Response must contain an array at quot; . quot;.quot; while making dropdown(如何删除此错误quot;响应必须在quot;处包含数组。创建下拉菜单时(Q;))
Why is it necessary to use `document.createElementNS` when adding `svg` tags to an HTML document via JS?(为什么在通过JS为一个HTML文档添加`svg`标签时,需要使用`Document.createElementNS`?)
wkhtmltopdf print-media-type uses @media print ONLY and ignores the rest(Wkhtmltopdf print-media-type仅使用@media print,而忽略其余内容)
price depend on selection of radio input(价格取决于无线电输入的选择)
calculate price depend on selection without button(根据没有按钮的选择计算价格)
Conditional formatting if a cell matches one from a list of a different sheet using Apps Script(如果单元格与使用Apps脚本的不同工作表列表中的单元格匹配,则设置条件格式)