【问题标题】:Find out the maximum number of decimal places within a string of numbers找出一串数字中的最大小数位数
【发布时间】:2020-11-17 17:09:06
【问题描述】:

字符串看起来像3*2.26+3.1*3.21(1+2)*3,1+(1.22+3)0.1+1+2.2423+2.1这样的东西,它可能会有所不同。我必须找到string 内小数位数最多的数字的小数位数。

我完全不知道该怎么做

【问题讨论】:

    标签: javascript string function char string-search


    【解决方案1】:

    您可以使用正则表达式查找所有有小数位的数字,然后使用Array.prototype.reduce 查找最多的小数位数。

    const input = '0.1+1+2.2423+2.1';
    
    const maxNumberOfDecimalPlaces = input
      .match(/((?<=\.)\d+)/g)
      ?.reduce((acc, el) =>
        acc >= el.length ?
        acc :
        el.length, 0) ?? 0;
    
    console.log(maxNumberOfDecimalPlaces);

    请注意,当在字符串中找不到带小数位的数字时,这将返回 0

    【讨论】:

      【解决方案2】:

      你可以使用正则表达式模式

      var str="6+3.1*3.21"
      d=str.match(/(?<=\d)[.]\d{1,}/g)
      d!=null ? res=d.map((n,i) => ({["number" + (i+1) ] : n.length - 1}))
      : res = 0
      console.log(res)

      【讨论】:

        【解决方案3】:

        您可以执行以下操作:

        上述方法似乎更健壮,因为它不涉及某些不受支持的功能:

        const src = ['3*2.2', '6+3.1*3.21', '(1+2)*3' , '1+(1.22+3)', '0.1+1+2.2423+2.1'],
        
              maxDecimals = s => 
               Math.max(
                ...s
                  .split(/[^\d.]+/)
                  .map(n => {
                    const [whole, fract] = n.split('.')
                    return fract ? fract.length : 0
                  })
               )
              
                
        src.forEach(s => console.log(`Input: ${s}, result: ${maxDecimals(s)}`))
        .as-console-wrapper{min-height:100%;}

        【讨论】:

        • 是的,非常感谢 =) 现在我开始理解它了 :)
        • @Sofia :我已经重新考虑了我的答案,使其更加稳健,因为它存在某些兼容性问题,就像您当前标记为接受的答案一样
        • 我的问题只是它对我来说不容易理解,我需要十进制数作为变量来使用并且无法快速弄清楚该怎么做
        • @Sofia :在我当前的解决方案中,有一个 fract 变量包含浮点数的小数部分,它使用非常基本的 RegExp,这比后向断言更容易理解,其余部分非常基本的.split().map(),所以如果您认为除了更强大之外(因为其他两种解决方案在某些流行的浏览器中可能根本失败)我当前解决方案更全面,请随时重新接受。
        • 好的,我现在就试试...我正要问另一个问题,关于我有 x 的正则表达式的问题]
        猜你喜欢
        • 2020-04-03
        • 1970-01-01
        • 1970-01-01
        • 2018-08-27
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多