Getting inaccurate results by entering numbers

const [shipping, setShipping] = useState({
        overseas: '3'
    })

    const handleChange = (e) => {
        setShipping({ overseas: e.target.value })  //can change to 8 or 3
    }
    const selection = shipping.overseas

console.log(selection)   // value of selection is accurate

    const getTotal = () => {
        return products.reduce((currentValue, nextValue) => {
            return  (currentValue + selection + nextValue.count * nextValue.price);
        }, 0);
    };

currentValue is 0 , selection is either 3 or 8 , nextValue is 23 when calculating the total, instead of adding the actual numbers, it became 0323 instead of 23+3 which is 26

Answer №1

Give parseInt() a shot:

const [shipping, setShipping] = useState({
        international: '5'
});

const handleInputChange = (e) => {
    setShipping({ international: e.target.value});  //can be changed to 8 or 3
};
const value = parseInt(shipping.international);

console.log(value);   // the selected value after parseInt is correct

const calculateTotal = () => {
    return items.reduce((currentTotal, nextItem) => {
        return  (currentTotal + value + nextItem.quantity * nextItem.price);
    }, 0);
};

The issue lies in JS interpreting "value" as a string, rather than a number. Therefore, it's "concatenating" instead of "adding".

Answer №2

It seems like the variable selection is being treated as a string, causing the mathematical operations to concatenate instead of sum. Therefore, 0 + '3' + 23 = 0323. To convert to a real number, try using Number(shipping.overseas) or +shipping.overseas

Answer №3

Here are some solutions for addressing the issue:

const selection = parseInt(shipping.overseas);

Alternatively, you can also try:

const selection =+shipping.overseas

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

"Upon querying with an AJAX POST request, the return value was

I'm encountering an issue where I am attempting to send data from JavaScript to PHP, make a database request, and have the result returned to my JS. However, all I get is "null" as a result. I have verified that my query is correct. Here is the JS cod ...

Modifying CSS files in real-time

I've been attempting to dynamically change the CSS file, but I've run into an issue: Whenever I try to alter the style, it seems to work correctly while in "debug mode", showing that the changes are applied. However, once the JavaScript function ...

I'm getting a "module not found" error - what's the solution?

const { getIo } = require('services/socketio'); const restful = require('utils/restful'); const publicApiService = require('services/publicApi'); const accessTokenMiddleware = require('middleware/accessToken'); const ...

Error: Functionality cannot be achieved

Looking for assistance in resolving this issue. Currently, I am attempting to register a new user and need to verify if the username already exists or not. Below is the factory code used for this purpose: .factory('accountService', function($res ...

What is the best way to bring in styles to a Next.js page?

I am facing an issue with my app where I have a folder called styles containing a file called Home.module.css. Every time I try to include the code in my pages/index.js, I encounter the same error message saying "404 page not found.." import styles from & ...

Utilizing JavaScript for loops to extract the final element from an array

I am facing an issue with the second loop within a function that goes through a JSON file. The problem is that it only returns the last item in the array. I need to figure out how to fix this because the chart object should be created on each iteration, ...

Challenges with ExpressJS 4 middleware

Trying to grasp the concept of middleware in ExpressJS 4 has been quite a challenge for me. As far as I understand, middleware are applied based on the order they are declared and can be "bound" at different levels. My current focus is on binding a middl ...

What is the best way to obtain the current time in a specific city?

Is there a simpler way to display the current time for a specific location without having to deal with factors like daylight savings time? I am searching for a more straightforward solution to always show the time for a particular city, zip code, or any o ...

Is there a method to directly download large files from the server without having to wait for the blob response?

I'm currently working on video file requests using axios. I have set the requests with responseType: blob to create a video player once the response is received with window.URL.createObjectUrl(). However, I also have a button that allows the user to d ...

Locating the Smallest Value in an Array of Objects

Looking at an object with keys containing arrays of objects that each have a price value. The goal is to find and return the lowest price value. In this scenario, aiming to return the value 8. Wondering if using the reduce method would be the best approach ...

Angular modules are designed to repeat chunks of code in a

Whenever I scroll the page, my function pushes items to an array. However, I am facing an issue where the pushed items are repeating instead of adding new ones. Solution Attempt onScroll(): void { console.log('scrolled'); var i,j,newA ...

Tips on implementing v-show within a loop

Hey @zero298, there are some key differences in the scenario I'm dealing with. My goal is to display all the items in the object array and dynamically add UI elements based on user input. Additionally, v-if and v-show function differently (as mentione ...

What is the best way to retrieve and display a PDF file through an API in VueJS?

I am looking to display a file from my API in my VueJS client. Specifically, when accessing a certain URL, the file (pdf, text, or image) should open if the browser supports it (similar to how Chrome opens PDFs). I want to achieve this using VueJS or just ...

Wrap every character in a span tag within this text

Extracting search strings from an object obj[item].coveredText and replacing each character with a span is what I aim to achieve. Currently, I can only replace the entire search string with a single span element. Any suggestions would be greatly appreciat ...

ng-view is the culprit behind the website's fatal error

Encountering a "RangeError: Maximum call stack size exceeded" in the console while trying to recreate a basic routing example from w3schools. The crash seems to be linked to <div ng-view></div> in index.html. Despite making minimal changes from ...

How can one achieve an explosion effect using jQuery?

Hey there! Here's a question to ponder... Let's assume we have a JavaScript variable set up like this: let myString = 'x,y,z'; let separated = myString.split(','); Now, imagine we have an HTML element like this: <ul id= ...

What is the reason for the regeneration of the 2D array?

I have a method called generateWeights() that retrieves random values in an array; And a method named learn() that calls the changeWeights() method to alter the values in the array. Expected: Prior to invoking the learn() method, I anticipate receiving an ...

Is there a viable substitute for websockets that can be utilized on shared hosting platforms?

Are there any viable alternatives for websockets that can be used with shared hosting? While I'm aware of node.js, socket.io, and Express.js, I'm unable to use them in a shared hosting environment. If there are other options available for creatin ...

Extracting the magnifying glass from the picture

After implementing a function to add a magnifying glass (.img-magnifier-glass) on button click, I am now looking to remove the glass by clicking the "cancel" button. However, I am unsure of how to write this function to interact with the "magnify" function ...

What is the best way to focus the video on its center while simultaneously cropping the edges to keep it in its original position and size?

I'm trying to create a special design element: a muted video that zooms in when the mouse hovers over it, but remains the same size as it is clipped at the edges. It would be even more impressive if the video could zoom in towards the point where the ...