CSS中取两位小数可以使用round()函数,该函数可以对数字进行四舍五入并保留指定小数位数。
.number {
width: 100px;
height: 40px;
line-height: 40px;
text-align: center;
border: 1px solid #ddd;
border-radius: 5px;
font-size: 24px;
font-weight: bold;
color: #333;
padding: 10px;
margin: 0 auto;
}
.rounded {
font-size: 18px;
color: #999;
}
.number::before {
content: "¥";
}
.number span {
font-size: 16px;
color: #666;
}
.number span::before {
content: ".";
}
.number span::after {
content: "%";
font-size: 12px;
}
.number.rounded span {
font-size: 18px;
color: #999;
} 以上代码是一个数字样式的预设,其中涉及到了四舍五入并保留两位小数的方法。
以下是使用round()函数对数字进行四舍五入并保留两位小数的方法:
.number span {
/* 假设数字为1.3586 */
content: " " round(1.3586 * 100) / 100;
/* 控制最终结果为1.36 */
} 在上述方法中,我们通过将数字乘以100,然后对其结果进行四舍五入保留2位小数即可得到结果1.36。
在实际应用中,您可以根据自己的需要更改样式,比如调整字体大小、颜色、设置小数点前后缀等。