简体   繁体   English

从字符串中删除多余的零

[英]Remove extra zeros from a string

I know the ways to remove leading zeros from string: 我知道从字符串中删除前导零的方法:

'000100'.replace(/^0+/, '')

But if a float like string (eg '00100.2300' or '00100'), how to remove all extra zeros from it? 但是,如果像字符串这样的浮点数(例如'00100.2300'或'00100'),如何从中删除所有多余的零?

'00100.2300' => '100.23'  
'00100' => '100'  
'00100.0023' => '100.0023'
'100.00' => '100.' or '100' will better
'-100.002300' => '-100.0023'
'0.50' => '0.5'

Assume the string: 假设字符串:

  • Only contains numbers or dot or negative symbol '-', no characters and others. 仅包含数字或点或负号“-”,不包含字符和其他字符。
  • The decimal point doesn't appear first in the string. 小数点不会出现在字符串的第一个位置。 And up to one. 最多一个。
  • The negative symbol '-' will appear in normal position. 负号“-”将出现在正常位置。 And no extra zeros before and after the '-'. 在“-”之前和之后都没有多余的零。
  • The float represented by the string may be larger than Number.MAX_SAFE_INTEGER 字符串表示的浮点数可能大于Number.MAX_SAFE_INTEGER
  • Both positive and negative float are possible. 正浮点数和负浮点数都是可能的。

A function used to filter extra zeros may be releatively easy and more steps also. 用于过滤多余零的函数可能相对容易,并且步骤也更多。

And a regexp will be simpler. 和一个正则表达式将更简单。

Regex: 正则表达式:

^0+(?!\.)|(?:\.|(\..*?))0+$

Live demo 现场演示

Breakdown: 分解:

  • ^0+(?!\\.) Match leading zeros that don't meet a decimal point ^0+(?!\\.)匹配不符合小数点的前导零
  • | Or 要么
  • (?: Start of non-capturing group (?:非捕获组的开始
    • \\. Match a decimal point 匹配小数点
    • | Or 要么
    • (\\..*?) Capture a decimal point preceding digits (\\..*?)捕获小数点后的数字
  • ) End of NCG ) NCG结束
  • 0*$ Match trailing zeros 0*$匹配尾随零

JS code: JS代码:

 var str = `00100.2300 00100 00100.0023 100.00 100. 00.50 0.5`; console.log( str.replace(/^0+(?!\\.)|(?:\\.|(\\..*?))0+$/gm, '$1') ) 

Something you can try is a native method: 您可以尝试的方法是本机方法:

parseFloat("000100.2300")

Then you can convert it back to the string with whatever method you want. 然后,您可以使用所需的任何方法将其转换回字符串。

You can use ^0+ to capture leading zeros and (\\.\\d*[1-9])(0+)$ to capture trailing zeros. 您可以使用^0+捕获前导零,并使用(\\.\\d*[1-9])(0+)$捕获尾随零。 So your regex should be: /^0+|(\\.\\d*[1-9])(0+)$/g 因此,您的正则表达式应为:/ /^0+|(\\.\\d*[1-9])(0+)$/g

 var res = '00100.2300'.replace(/^0+|(\\.\\d*[1-9])(0+)$/g, '$1'); console.log(res); var res2 = '100'.replace(/^0+|(\\.\\d*[1-9])(0+)$/g, '$1'); console.log(res2); 

It occurs to me you can do a single find and replace to accomplish 在我看来,您可以执行一次查找和替换操作即可完成
everything. 一切。

With this, you match the entire valid number at a time, enabling you to 这样,您一次就能匹配整个有效数字,从而使您能够
fix multiple numbers in a single string, if done globally. 如果在全局范围内完成,则在单个字符串中固定多个数字。
Also works the same if your string contains a single number. 如果您的字符串包含单个数字,则也可以使用相同的功能。

Find (?:(-)(?![0.]+(?![\\d.]))|-)?\\d*?([1-9]\\d*|0)(?:(?:(\\.\\d*[1-9])|\\.)\\d*)?(?![\\d.]) 查找(?:(-)(?![0.]+(?![\\d.]))|-)?\\d*?([1-9]\\d*|0)(?:(?:(\\.\\d*[1-9])|\\.)\\d*)?(?![\\d.])
Replace $1$2$3 替换$1$2$3

JS demo: https://regex101.com/r/H44t6z/1 JS演示: https//regex101.com/r/H44t6z/1

Readable / Info version 可读/信息版本

 # Add behind boundary check here
 # -----------------
 (?:
      ( - )                         # (1), Preserve sign -
      (?!                           # Only if not a zero value ahead
           [0.]+ 
           (?! [\d.] )
      )
   |                              # or
      -                             # Match sign, but dump it
 )?
 \d*?                          # Dump leading 0's
 (                             # (2 start), Preserve whole number 
      [1-9]                         # First non-0 number
      \d*                           # Any number
   |                              # or
      0                             # Just last 0 before decimal
 )                             # (2 end)
 (?:                           # Optional fraction part
      (?:                           # -------------
           (                             # (3 start), Preserve decimal and fraction
                \.                            # Decimal
                \d*                           # Any number
                [1-9]                         # Last non-0 number
           )                             # (3 end)
        |                              # or
           \.                            # Match decimal, but dump it
      )                             # -------------
      \d*                           # Dump trailing 0's
 )?
 (?! [\d.] )                   # No digits or dot ahead

This answer solve task even if string 100 is passed: 即使传递了字符串100此答案也可以解决任务:

'00100.002300'.replace(/^0+|(\.0*\d+[^0]+)0+$/g, '$1')

100.0023 100.0023

'00100'.replace(/^0+|(\.0*\d+[^0]+)0+$/g, '$1')

100 100

It might be an idea to use JS type coercion here. 在这里使用JS类型强制可能是一个主意。

 var trim = s => +s+'', strs = ['00100.2300','00100','00100.0023','100.0023'], res = strs.map(trim); console.log(res); 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM