Home > Web Front-end > JS Tutorial > body text

Vue custom filter formats three digits plus a comma implementation code

亚连
Release: 2018-05-26 15:27:48
Original
3148 people have browsed it

这篇文章主要介绍了Vue自定义过滤器格式化数字三位加一逗号的实现代码,需要的朋友可以参考下

前端处理一些金额,数字类的数据要求按照固定的格式显示,比如9,527,025,或者带有小数(如1,587.23)仍要三位一断。有些话也不必多说,既然要求如此,实现呗。

作为前端主流框架之一的Vue,类似的功能肯定都有人写的很完善了。我呢,最讨厌不动脑筋去网上找现成的,所以我自己写了一个。话不多说,先放效果图再贴代码(为了展现思路,我面向过程写的,另外这个是针对保留两位小数的数字进行过滤,因为保留整数的太简单了)。

<!DOCTYPE html>
<html>
 <head>
  <meta charset="UTF-8">
  <meta http-equiv="Content-Type" content="text/html">
  <title>Vue数字过滤器逢三一断</title>
 </head>
 <body>
  <p id="app">
   <h4>说明:这个版本是针对保留两位小数的浮点数进行过滤格式化的</h4>
   <input type="number" v-model="num" />
   <p>{{num|NumFormat}}</p>
  </p>
 </body>
 <script type="text/javascript" src="vue.js"></script>
 <script>
  Vue.filter(&#39;NumFormat&#39;, function(value) {
   if(!value) return &#39;0.00&#39;;
   var intPart = Number(value).toFixed(0); //获取整数部分
   var intPartFormat = intPart.toString().replace(/(\d)(?=(?:\d{3})+$)/g, &#39;$1,&#39;); //将整数部分逢三一断
   var floatPart = ".00"; //预定义小数部分
   var value2Array = value.split(".");
   //=2表示数据有小数位
   if(value2Array.length == 2) {
    floatPart = value2Array[1].toString(); //拿到小数部分
    if(floatPart.length == 1) { //补0,实际上用不着
     return intPartFormat + "." + floatPart + &#39;0&#39;;
    } else {
     return intPartFormat + "." + floatPart;
    }
   } else {
    return intPartFormat + floatPart;
   }
  })
  var app = new Vue({
   el: "#app",
   data: {
    num: 0
   },
  })
 </script>
</html>
Copy after login

上面是我整理给大家的,希望今后会对大家有帮助。

相关文章:

使用对象封装ajax重复调用的方法

基于iframe实现ajax跨域请求 获取网页中ajax数据

Ajax发送和接收请求

The above is the detailed content of Vue custom filter formats three digits plus a comma implementation code. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!