James
James

Reputation: 15

How to use replace() as adding '.' between the numbers?

Using Javascript, if my number is 5899, I want to insert a decimal point between the numbers to get the result of 58.99. I know (num/100).toFixed(2) would work, but just wondering if there is a way for using replace.

Upvotes: 0

Views: 92

Answers (1)

CertainPerformance
CertainPerformance

Reputation: 370619

A regular expression can look ahead for 2 digits followed by the end of the string...

console.log(
  String(5899).replace(
    /(?=\d{2}$)/,
    '.'
  )
);

but .toFixed makes a lot more intuitive sense, and so should probably be preferred.

Upvotes: 7

Related Questions