Hanz
Hanz

Reputation: 519

chaining to cast type in javascript

   let finalPrice = room.points[0].price.finalPrice //string
   finalPrice = +finalPrice //number
   finalPrice = finalPrice.toFixed(2) //2 decimal

Is it possible to shorten above type casting?

if I do

+room.points[0].price.finalPrice.toFixed(2)

I'll get this error: toFixed is not a function

Upvotes: 1

Views: 119

Answers (1)

Snow
Snow

Reputation: 4097

Like this:

const finalPrice = Number(room.points[0].price.finalPrice).toFixed(2);

No need for intermediate variables.

The problem with your + is that it has lower operator precedence than the . with the .toFixed call.

Upvotes: 8

Related Questions