zoukankan      html  css  js  c++  java
  • 一道面试题引起的好奇:数字千分位

      一道面试题引起的好奇:

        题目:12000000.11 如何将浮点数小数点左边的数每三位加一个逗号,如12,000,000.11?

       答案:

    function commafy(num){
      return num && num.toString().replace(/(d)(?=(d{3})+.)/g, function($1, $2){
        return $2 + ',';
      });
    }
    console.log(12000000.11) // 12,000,000.11
    console.log(112000000.11) //
    112,000,000.11
    console.log(-112000000.11) // -112,000,000.11

      利用了字符串的replace方法及正则实现。

     用前向声明和分组,第二个()从后往前匹配3位数字,即$2。每匹配到一个$2就在后面加上逗号,返回。

        满足题目要求,但是实际中会存在数字不带小数点的情况,上面的实现方式就无法满足了。修改了一下,支持不带小数点的数字。

     用前向声明和非前向声明,从后往前匹配3位数字,向前声明的地方替换成逗号,但是如果刚好是3的倍数位,会第一位前面也加,,所以前面要再来个非前向声明。

    // 数字千分位
    function commafy (num) {
      if (isNaN(Number(num))) {
        return num
      }
      if (num && num.toString().indexOf('.') > 0) {
        return num.toString().replace(/(d)(?=(d{3})+.)/g, ($0, $1) => {
          return $1 + ','
        })
      } else {
        return num && num.toString().replace(/(?=(?!())(d{3})+$)/g, ',')
      }
    }
    console.log(12000000.11) // 12,000,000.11
    console.log(112000000.11) // 112,000,000.11
    console.log(-112000000.11) // -112,000,000.11
    
    
    console.log(12000000) // 12,000,000
    console.log(112000000) // 112,000,000
    console.log(-112000000) // -112,000,000
  • 相关阅读:
    八数码难题 (codevs 1225)题解
    小木棍 (codevs 3498)题解
    sliding windows (poj 2823) 题解
    集合删数 (vijos 1545) 题解
    合并果子 (codevs 1063) 题解
    等价表达式 (codevs 1107)题解
    生理周期 (poj 1006) 题解
    区间 (vijos 1439) 题解
    区间覆盖问题 题解
    种树 (codevs 1653) 题解
  • 原文地址:https://www.cnblogs.com/EnSnail/p/8477825.html
Copyright © 2011-2022 走看看