Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
491 views
in Technique[技术] by (71.8m points)

js 数字 转换 百 千 万 亿显示

比如后台返回1000 前端显示1千
比如后台返回10000 前端显示1万
比如后台返回100000 前端显示10万
比如后台返回1000000 前端显示100万
比如后台返回10000000 前端显示1000万
比如后台返回100000000 前端显示10000万

如何写一个函数 请教 可保留小数点 也可以不要小数点


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)
var changeUnit = function(value) {
          let newValue = ['', '', ''];
          let fr = 1000;
          const ad = 1;
          let num = 3;
          const fm = 1;
          while (value / fr >= 1) {
            fr *= 10;
            num += 1;
            // console.log('数字', value / fr, 'num:', num);
          }
          if (num <= 4) { // 千
            newValue[1] = '千';
            newValue[0] = parseInt(value / 1000) + '';
          } else if (num <= 8) { // 万
            const text1 = parseInt(num - 4) / 3 > 1 ? '千万' : '万';
            // tslint:disable-next-line:no-shadowed-variable
            const fm = '万' === text1 ? 10000 : 10000000;
            newValue[1] = text1;
            newValue[0] = (value / fm) + '';
          } else if (num <= 16) {// 亿
            let text1 = (num - 8) / 3 > 1 ? '千亿' : '亿';
            text1 = (num - 8) / 4 > 1 ? '万亿' : text1;
            text1 = (num - 8) / 7 > 1 ? '千万亿' : text1;
            // tslint:disable-next-line:no-shadowed-variable
            let fm = 1;
            if ('亿' === text1) {
              fm = 100000000;
            } else if ('千亿' === text1) {
              fm = 100000000000;
            } else if ('万亿' === text1) {
              fm = 1000000000000;
            } else if ('千万亿' === text1) {
              fm = 1000000000000000;
            }
            newValue[1] = text1;
            newValue[0] = parseInt(value / fm) + '';
          }
          if (value < 1000) {
            newValue[1] = '';
            newValue[0] = value + '';
          }
          return newValue.join('');
        }

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...