Search code examples
javascriptfloating-pointnumber-formattingstring-concatenation

In Javascript numbers with only double zeros in their decimal place lost their double zero when converted to String ? Why?


I am developing a web app in which I need to concat some numbers as String format

One of the number need 00 at decimal place if it is whole number (ex 15.00)

But when I concat it with other number , the 00 got lost (ex 15.00 => 15)

An example :

const price = 15.00;
const period = 3;
const CC = 840;

const concated = `${price}${period}${CC}`;
console.log(concated);
const saltedHash = crypto.createHash('md5').update(`${concated}GhVT+6FySEgWVeUWCHLo2lks`).digest('hex');

post[0].saltedHash = saltedHash;
post[0].string = `${concated}GhVT+6FySEgWVeUWCHLo2lks`;

Now the problem is , the constant concated contains 153840 instead of 15.003840

Why this problem occurring ?

How to preserve 00s?


Solution

  • You can achieve that by using toFixed(), something like:

    const concated = `${price.toFixed(2)}${period}${CC}`;
    

    const price = 15.00;
    const period = 3;
    const CC = 840;
    
    const concated = `${price.toFixed(2)}${period}${CC}`;
    console.log(concated);

    The issue is that when you use a template literal it converts the number to string, i.e. String(15) === "15", whereas when you do 15..toFixed(2) it "returns a string representing a number in fixed-point notation".

    Thus, 15..toFixed(2) === "15.00", i.e. typeof 15.00.toFixed(2) === "string"