If we have some s
string representation of a number, which we can get for example using the .toFixed(digits)
method of Number (or by any other means), then for removal of insignificant trailing zeros from the s
string we can use:
s.replace(/(\.0*|(?<=(\..*))0*)$/, '')
/**********************************
* Results for various values of s:
**********************************
*
* "0" => 0
* "0.000" => 0
*
* "10" => 10
* "100" => 100
*
* "0.100" => 0.1
* "0.010" => 0.01
*
* "1.101" => 1.101
* "1.100" => 1.1
* "1.100010" => 1.10001
*
* "100.11" => 100.11
* "100.10" => 100.1
*/
Regular expression used above in the replace()
is explained below:
|
operator inside the regular expression, which stands for "OR", so, the replace()
method will remove from s
two possible kinds of substring, matched either by the (\.0*)$
part OR by the ((?<=(\..*))0*)$
part.(\.0*)$
part of regex matches a dot symbol followed by all the zeros and nothing else till to the end of the s
. This might be for example 0.0
(.0
is matched & removed), 1.0
(.0
is matched & removed), 0.000
(.000
is matched & removed) or any similar string with all the zeros after the dot, so, all the trailing zeros and the dot itself will be removed if this part of regex will match.((?<=(\..*))0*)$
part matches only the trailing zeros (which are located after a dot symbol followed by any number of any symbol before start of the consecutive trailing zeros). This might be for example 0.100
(trailing 00
is matched & removed), 0.010
(last 0
is matched & removed, note that 0.01
part do NOT get matched at all thanks to the "Positive Lookbehind Assertion", i.e. (?<=(\..*))
, which is in front of 0*
in this part of regex), 1.100010
(last 0
is matched & removed), etc.100
or 100.11
, etc. So, if an input does not have any trailing zeros then it stays unchanged.Some more examples using .toFixed(digits)
(Literal value "1000.1010" is used in the examples below, but we can assume variables instead):
let digits = 0; // Get `digits` from somewhere, for example: user input, some sort of config, etc.
(+"1000.1010").toFixed(digits).replace(/(\.0*|(?<=(\..*))0*)$/, '');
// Result: '1000'
(+"1000.1010").toFixed(digits = 1).replace(/(\.0*|(?<=(\..*))0*)$/, '');
// Result: '1000.1'
(+"1000.1010").toFixed(digits = 2).replace(/(\.0*|(?<=(\..*))0*)$/, '');
// Result: '1000.1'
(+"1000.1010").toFixed(digits = 3).replace(/(\.0*|(?<=(\..*))0*)$/, '');
// Result: '1000.101'
(+"1000.1010").toFixed(digits = 4).replace(/(\.0*|(?<=(\..*))0*)$/, '');
// Result: '1000.101'
(+"1000.1010").toFixed(digits = 5).replace(/(\.0*|(?<=(\..*))0*)$/, '');
// Result: '1000.101'
(+"1000.1010").toFixed(digits = 10).replace(/(\.0*|(?<=(\..*))0*)$/, '');
// Result: '1000.101'
To play around with the above regular expression used in replace()
we can visit: https://regex101.com/r/owj9fz/1