css中数字保留两位小数

admin 轻心小站 关注 LV.19 运营
发表于前端技术学习版块 css,教程

CSS中数字保留两位小数是很常用的需求,尤其在涉及货币和数字数据时,精度尤为重要。下面介绍几种实现方法。1.使用toFixed() .box { font-size: 1.5rem; color: r

CSS中数字保留两位小数是很常用的需求,尤其在涉及货币和数字数据时,精度尤为重要。下面介绍几种实现方法。

1.使用toFixed()

 .box {
    font-size: 1.5rem;
    color: red;
  }

  .box::before {
    content: '$';
  }

  .price {
    width: 100px;
    display: inline-block;
  }

  var number = 123.456;
  var price = number.toFixed(2);

  document.querySelector('.price').textContent = price; 

toFixed()用于将数字转换为字符串,并指定小数位数,返回结果为字符串。在上面的例子中,将数字123.456转换为字符串,保留两位小数,结果为123.46。

2.使用Math.round()

 .box {
    font-size: 1.5rem;
    color: red;
  }

  .box::before {
    content: '$';
  }

  .price {
    width: 100px;
    display: inline-block;
  }

  var number = 123.456;
  var price = Math.round(number * 100) / 100;

  document.querySelector('.price').textContent = price; 

使用Math.round()将数字进行四舍五入,乘以100后再除以100,实现保留两位小数。在上面的例子中,将数字123.456进行四舍五入,结果为123.46。

3.使用CSS属性

 .price {
    width: 100px;
    display: inline-block;
    background-color: yellow;
    padding: 10px;
    text-align: right;
    border-radius: 5px;
  }

  .price::before {
    content: '$';
  }

  .price::after {
    content: attr(data-num);
  } 

三种方式中,第三种方式最为简单,使用CSS属性attr()来获取元素的自定义属性data-num的值,并添加到元素的::after伪元素中,即可实现在页面中保留两位小数显示数字。

以上是CSS中数字保留两位小数的实现方法,大家可以根据实际需要选择最适合自己的方式进行实现。

文章说明:

本文原创发布于探乎站长论坛,未经许可,禁止转载。

题图来自Unsplash,基于CC0协议

该文观点仅代表作者本人,探乎站长论坛平台仅提供信息存储空间服务。

评论列表 评论
发布评论

评论: css中数字保留两位小数

粉丝

0

关注

0

收藏

0

已有0次打赏