Walker
Walker

Reputation: 134443

Adjusting Regex to remove trailing decimal point + zeroes if there is no fraction

I'm trying to learn Regex.

Currently I'm trying to write a function that parses a float and sets a "maximum" number of decimal places (basically only allows two decimal points, but doesn't add them if there is no content - i.e. gets rid of the 0's in X.00 to return X.). Here's the code:

price_var.toFixed(2).replace(/0{0,2}$/, "");

It works well removing the zeros, but doesn't remove the decimal place. Is there a way to also get rid of the decimal place if there is no fraction?

Upvotes: 0

Views: 2533

Answers (1)

Prince John Wesley
Prince John Wesley

Reputation: 63688

price_var.toFixed(2).replace(/\.0{0,2}$/, ""); 

since it is a fixed decimal points, try

price_var.toFixed(2).replace(/\.0{2}$/, ""); 

or

price_var.toFixed(2).replace(/\.00$/, ""); 

Upvotes: 5

Related Questions