0

I have written a simple function that converts Celsius degrees to Fahrenheit degrees. The function does not display errors, and all degrees are correctly converted.(This is an exercise from the JavaScript course I'm taking. The Celsius and temp variables were supposed to be defined outside the function.)

let celcius;
let temp;

    const fahrenheit = (param) => {
        celcius = param;
        temp = celcius * 1.8 + 32;
        console.log(`${celcius}°C = ${temp}°F`);
}
fahrenheit(param);

But I have noticed that calling this function with certain numbers logs Fahrenheit degrees in the console with 14 decimal places. So I changed the code a bit and using a for loop, I printed all Celsius degrees from 0 to 50.

let celcius;
let temp;

const fahrenheit = () => {
    for (celcius = 0; celcius < 51; celcius++) {
        temp = celcius * 1.8 + 32;
        console.log(`${celcius}°C = ${temp}°F`);
    }
}
fahrenheit()

Here's the output in the console:

0°C = 32°F
1°C = 33.8°F
...
13°C = 55.400000000000006°F
...
21°C = 69.80000000000001°F
...
26°C = 78.80000000000001°F
...
31°C = 87.80000000000001°F
...
37°C = 98.60000000000001°F
...
42°C = 107.60000000000001°F
...
47°C = 116.60000000000001°F
...
50°C = 122°F

I wonder what could be the reason for this.

Of course, I can use the .toFixed(2) method to round everything to two decimal places, but that's just solving the problem, not understanding why the problem occurred in the first place. I don't understand why only some degrees cause 14 decimal places to appear, while others don't.

j08691
  • 204,283
  • 31
  • 260
  • 272

0 Answers0