likes
comments
collection
share

分转元

作者站长头像
站长
· 阅读数 46

简单明了

const fenToyuan = (n) => {
  const s = String(n);
  const len = s.length;
  if (len === 1) {
    return '0.0' + s;
  } else if (len === 2) {
    return '0.' + s;
  } else {
    return s.substring(0, len - 2) + '.' + s.substring(len - 2);
  }
};

比较复杂的方案

const toDecimal2 = (x) => {
  var f = parseFloat(x);
  if (isNaN(f)) {
    return false;
  }
  var f = Math.round(x * 100) / 100;
  var s = f.toString();
  var rs = s.indexOf('.');
  if (rs < 0) {
    rs = s.length;
    s += '.';
  }
  while (s.length <= rs + 2) {
    s += '0';
  }
  return s;
};

const FenToYuan = (fen) => {
  var num = fen;
  num = fen * 0.01;
  num += '';
  var reg =
    num.indexOf('.') > -1
      ? /(\d{1,3})(?=(?:\d{3})+\.)/g
      : /(\d{1,3})(?=(?:\d{3})+$)/g;
  num = num.replace(reg, '$1');
  num = toDecimal2(num);
  return num;
};

// 验证100 - 10000000 没问题
for (let i = 100; i < 10000000; i++) {
  const n = FenToYuan(i);
  const s = String(i);
  const t = n.replace(/\./g, '');
  if (s !== t) {
    console.log(i, n);
  }
}
console.log('验证结束');


转载自:https://juejin.cn/post/7099650508591202341
评论
请登录