微信小程序,格式化千分位并保留两位小数

1、新建utils.wxs

//逢三位转逗号,保留两位小数,支持负数
var threeNumForTwo = {
  money_three_for_two_thousands: function(num) {
    //num = parseInt(num);
    
    var num = num + '';
    var d = '';
    if (num.slice(0, 1) == '-'){
      d = num.slice(0, 1);
      num = num.slice(1);
    }
    var len = num.length;
    var index = num.indexOf('.');
    if (index == -1) {
      num = num + '.00';
    } else if ((index + 2) == len) {
      num = num + '0';
    }
    var index = num.indexOf('.'); // 字符出现的位置
    var num2 = num.slice(-3);
    num = num.slice(0,index)
    var result = '';
    while (num.length > 3) {
      result = ',' + num.slice(-3) + result;
      num = num.slice(0, num.length - 3);
    }
    if (num) {
      result = num + result;
    }
    return d + (result + num2);
  }
}

module.exports = {
  money_three_for_two_thousands: threeNumForTwo.money_three_for_two_thousands //暴露接口调用
}

2、在使用的wxml引入,部分wxml代码

<wxs module="threeNumForTwo" src="../../utils/util.wxs"></wxs>
<include src="/commons/navbar/navbar" />
<view class="after-navber">
  <view class="zr">
    <view class='user_box' hidden="{{isShowInfo}}">

      <view class='user-info'>
        <view class='user-box'>
          <view class='avatar'>
            <image src="{{avatar_url ? avatar_url : '../../images/icon-user-default-header.png'}}"></image>
          </view>
          <view class='user-name'>
            <block wx:if="{{user_center}}">
              <view>
                <text>{{user_center.FRealName || ''}}</text>
                <text>({{user_center.FUserName || ''}})</text>
              </view>
              <view class="total-funds">资金总额:¥{{threeNumForTwo.money_three_for_two_thousands(user_center.FTotalFunds) || 0.00}}</view>
            </block>
            <!-- <block wx:else>
              <text class="user-logo-box" bindtap="login">登录/注册</text>
            </block> -->
          </view>
        </view>
      </view>
    </view>

3、使用

{{threeNumForTwo.money_three_for_two_thousands(user_center.FTotalFunds) || 0.00}}
发布了264 篇原创文章 · 获赞 98 · 访问量 87万+

猜你喜欢

转载自blog.csdn.net/lengyue1084/article/details/104804462