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

Dan*_*mms 32 html css format

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

<!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>
Run Code Online (Sandbox Code Playgroud)

这个例子如下:

纯CSS:25153.3美元

理想格式:25,153.30美元

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

ozk*_*ary 20

货币格式可以通过CSS和一些Javascript来实现,这是解析数字以添加逗号所需的.CSS类添加了额外的样式,如负(红色)或货币符号(即$ Dollar sign).方法如下:

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

Number(value).toLocaleString('en');
Run Code Online (Sandbox Code Playgroud)

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

.enMoney::before {
    content:"$";
}
.negMoney {
    color:red;
}
Run Code Online (Sandbox Code Playgroud)

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

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


Tim*_*ene 13

var number = 25153.3; console.log(number.toLocaleString()); /------

var number = 25153.3;
result="$ " + number.toLocaleString(undefined, {minimumFractionDigits: 2, maximumFractionDigits: 2})
console.log(result);

console.log();
//---------------------------------------------------

// request a currency format
console.log(number.toLocaleString('us-US', { style: 'currency', currency: 'USD' }));
// ? $ 251,52.30 

console.log(number.toLocaleString('de-DE', { style: 'currency', currency: 'EUR' }));
// ? 25.152,30 €

// the Japanese yen doesn't use a minor unit
console.log(number.toLocaleString('ja-JP', { style: 'currency', currency: 'JPY' }))
// ? ?251,53
Run Code Online (Sandbox Code Playgroud)

  • 不,不是,因为它没有提供 OP 所要求的内容 (12认同)
  • 这是 javascript,不是 css。 (3认同)
  • 但这是一个更好的解决方案。 (2认同)

pen*_*tur 4

如果您询问 CSS 中的数字格式(即从字符串中解析数字,然后使用千位分隔符、小数分隔符、固定十进制数字等对其进行格式化),那么不,这在 CSS 中是不可能的,这是这不是 CSS 的设计目的。

如果您想进行任何格式化,那么您最好使用 XSLT。例如:

<?xml version="1.0" encoding="ISO-8859-1"?>
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">

    <xsl:template match="span[@class='dollars']">
        <span>
            <xsl:text>$</xsl:text>
            <xsl:value-of select="format-number(current(), '###,###.00')"/>
        </span>
    </xsl:template>

    <xsl:template match="@* | node()">
        <xsl:copy>
            <xsl:apply-templates select="@* | node()"/>
        </xsl:copy>
    </xsl:template>
</xsl:stylesheet>
Run Code Online (Sandbox Code Playgroud)

  • “这不是 CSS 的设计目的”...我对 CSS 的设计目的保留判断。将通用功能推送到浏览器正是 CSS 等技术的设计目的。曾经有一段时间,“响应屏幕尺寸”“不是 CSS 的设计目的”另外:http://wiki.csswg.org/ideas/content-formatting (81认同)
  • “格式化数字”是一种表示功能,而这“正是”CSS 的设计目的。 (41认同)
  • 啊哈 - 所以 *这就是 XSLT 的设计目的;-) (8认同)