hellodolly
hellodolly

Reputation: 149

How do you remove a trailing decimal zero in middle of string?

Suppose I have a string: "Trump spent $1.50 billion dollars for his campaign."

How would I remove the trailing zero?

I thought str.replace('/(\.[0-9]{1})0+\s/g',"$1"); would work but doesn't strip it. Any help please?

Upvotes: 3

Views: 57

Answers (3)

Thomas
Thomas

Reputation: 3593

parse every float and stringify it again:

str.replace(/\d+\.\d+/g, Number);

Upvotes: 0

elixenide
elixenide

Reputation: 44851

You're trying to use a regex (/.../g), but you're actually using a string literal ('/.../g'). Remove the 's:

str.replace(/(\.[0-9]{1})0+\s/g, "$1");

Upvotes: 4

Vivin Paliath
Vivin Paliath

Reputation: 95598

Try:

str.replace(/(\.[0-9]*[^0])0+/g, "$1");

This will handle cases like $1.040 or $1.120 as well.

Upvotes: 1

Related Questions