Connor Flynn
Connor Flynn

Reputation: 17

How do i round a variables value down to a whole number in JS?

I'm creating a calculator that takes weight, location, and quantity as a parameter. I have the prices set as key value pairs, and when a weight is entered it will iterate over the object array, find the key that is equal to it, and display a message of the price using the value. The problem i'm running into is whenever a number is entered that isn't a whole number, nothing is displayed back. The following is my code:

const calculateRate = () => {
        let price
        let ausWeight = {
            1: 19, 2: 25, 3: 25, 4: 28, 5: 28, 6: 31.5, 7: 35, 8: 38.5, 9: 42, 10: 45.5, 11: 49, 12: 52.5, 13: 56, 14: 59.5,
            15: 63, 16: 66.5, 17: 70, 18: 73.5, 19: 77, 20: 80.5};
        let inputWeight = Object.keys(ausWeight)
        let inputValue = Object.values(ausWeight)
        let x = Math.floor(weight);
        console.log(x)
        
        for (var i = 0; i < inputWeight.length; i++){
            if (x === inputWeight[i] && region.value === 'Australia') {
                price = `Estimated delivery cost is $${inputValue[i] * quantity}`;
                setShowResults(true)
                setPrice(price); 
            }
        }
}

As you can see, i'm setting x to equal to weight rounded down with Math.floor(), but i'm not getting an output. You can also see that i'm logging the value of x to the console and it's giving the result i'm expecting when i look at it through dev tools. For context, this is a functional react component, with weight being set by setState().

Any idea's on how to fix this would be appreciated. Thanks.

Upvotes: 1

Views: 49

Answers (1)

Nina Scholz
Nina Scholz

Reputation: 386550

You simply compare a string with a number.

By using Object.keys, you get an array of strings. But later you take a strict comparing.

To overcome this, you need to convert the string value into a number

x === +inputWeight[i] 

Upvotes: 2

Related Questions