且构网

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

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

更新时间:2023-02-10 12:01:03

货币格式可以使用CSS和一些Javascript这是解析数字以添加逗号所需要的。 CSS类添加附加样式,如负(红色)或货币符号(即$美元符号)。方法如下:



1)将值转换为数字(根据区域设置添加逗号)

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

2)添加一个类以确定它是负值还是正值(即红色) p>

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

使用示例代码和css查看更多细节:



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


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>

That example comes out as:

Pure CSS: $25153.3

Ideal format: $25,153.30

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

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) Convert the value to number (adds the commas based on the locale)

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

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

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

See more detail here with the sample code and css:

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