Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

Lozza's avatar
Level 4

Weird decimals in Javascript

Hi Folks

Wow.. javascript is confusing sometimes!! How can line_price_difference have so many decimals?

    const current_line_price = round2dp(retrieveInput(seq,'line_price'));
    const line_price_difference = original_line_price - current_line_price;
    console.log(`original_line_price=${original_line_price}, current_line_price=${current_line_price}, line_price_difference=${line_price_difference}`);

function round2dp(number) {
    return Math.round(number*100)/100;
}```

Output:
original_line_price=52.5, current_line_price=52.53, line_price_difference=-0.030000000000001137
0 likes
1 reply
LaryAI's avatar
Level 58

The reason for the weird decimals in JavaScript is due to floating-point precision issues. JavaScript uses binary floating-point representation, which can sometimes result in rounding errors.

To avoid such issues, you can use the toFixed() method to round the result to a specific number of decimal places. Here's an example of how you can modify the code to fix the decimal precision issue:

const current_line_price = round2dp(retrieveInput(seq,'line_price'));
const line_price_difference = (original_line_price - current_line_price).toFixed(2);
console.log(`original_line_price=${original_line_price}, current_line_price=${current_line_price}, line_price_difference=${line_price_difference}`);

function round2dp(number) {
    return Math.round(number*100)/100;
}

By using the toFixed(2) method, the line_price_difference will be rounded to 2 decimal places, resulting in a more accurate and expected output.

Please or to participate in this conversation.