I know the ways to remove leading zeros from string:
'000100'.replace(/^0+/, '')
But if a float like string (e.g. '00100.2300' or '00100'), how to remove all extra zeros from it?
'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
- 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.
I know the ways to remove leading zeros from string:
'000100'.replace(/^0+/, '')
But if a float like string (e.g. '00100.2300' or '00100'), how to remove all extra zeros from it?
'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
- 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.
Share Improve this question edited May 14, 2018 at 15:55 junlin asked May 13, 2018 at 15:06 junlinjunlin 2,0452 gold badges29 silver badges40 bronze badges 4- is it possible the string contains characters and not only numbers? – johnny 5 Commented May 13, 2018 at 15:09
- Use this : '00100.2300' .replace(/^0*/, ' ') – Adya Commented May 13, 2018 at 15:11
- YourString.replace("0", ""); didn't test it but might work – Daan Seuntjens Commented May 13, 2018 at 15:11
-
Try
^0+|(\..*?)0+$
and replace with$1
. Check here regex101./r/U2dwtd/1 – revo Commented May 13, 2018 at 15:57
7 Answers
Reset to default 5Regex:
^0+(?!\.)|(?:\.|(\..*?))0+$
Live demo
Breakdown:
^0+(?!\.)
Match leading zeros that don't meet a decimal point|
Or(?:
Start of non-capturing group\.
Match a decimal point|
Or(\..*?)
Capture a decimal point preceding digits
)
End of NCG0*$
Match trailing zeros
JS code:
var str = `00100.2300
00100
00100.0023
100.00
100.
00.50
0.5`;
console.log(
str.replace(/^0+(?!\.)|(?:\.|(\..*?))0+$/gm, '$1')
)
It occurs to me you can do a single find and replace to acplish
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.])
Replace $1$2$3
JS demo: https://regex101./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
You can use ^0+
to capture leading zeros and (\.\d*[1-9])(0+)$
to capture trailing zeros. So your regex should be: /^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);
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.
This answer solve task even if string 100
is passed:
'00100.002300'.replace(/^0+|(\.0*\d+[^0]+)0+$/g, '$1')
100.0023
'00100'.replace(/^0+|(\.0*\d+[^0]+)0+$/g, '$1')
100
It might be an idea to use JS type coercion here.
var trim = s => +s+'',
strs = ['00100.2300','00100','00100.0023','100.0023'],
res = strs.map(trim);
console.log(res);
I had float numbers in a string type and for data parison from two different sources, I just needed to trim the trailing zeroes from numbers.
Using a regex seemed more prone for errors to me. Using a simple while loop checking whether the last character was a zero or not seemed like a sufficient check for me for a one-off script.
// Conversion example: "2.450" to "2.45"
// "3.200" to "3.2"
function removeTrailingZero(percentage) {
let ret = percentage;
while (ret.charAt(ret.length - 1) === '0' || ret.charAt(ret.length - 1) === '.') {
ret = ret.slice(0, -1);
}
return ret;
}