Performing the addition operation on two floating point numbers in JavaScript

The JavaScript code goes as follows:

var receivedamt = parseFloat($('#cashRecText').val()).toFixed(2); 
console.log(receivedamt);
var addon = parseFloat('5.00').toFixed(2);
console.log(addon);
addon = parseFloat(receivedamt).toFixed(2) + parseFloat(addon).toFixed(2);
console.log(addon);

However, the output shows:

3.00
5.00
3.005.00

How can we achieve a sum of

8.00

Answer №1

let sum = (parseFloat(inputamt)+parseFloat(extra)).toFixed(2);

UPDATE: The issue with the initial code not functioning correctly was due to the toFixed method returning a string instead of a float. Consequently, the operation resulted in concatenating strings rather than adding float values.

Answer №2

Give this a shot:

totalAddOn = parseFloat(receivedAmount) + parseFloat(addOn);

Answer №3

function addDecimalNumbers(a, b) {
    const arr1 = a.toString().split('');
    const arr2 = b.toString().split('');

    let dotPos1 = arr1.indexOf('.');
    if(dotPos1 < 0){
        arr1.push(".");
        arr1.push("0");
        dotPos1 = arr1.indexOf('.');
    }
    let dotPos2 = arr2.indexOf('.');
    if(dotPos2 < 0){
        arr2.push(".");
        arr2.push("0");
        dotPos2 = arr2.indexOf('.');
    }
    const dotPos = Math.max(dotPos1, dotPos2);
    let diff1 = dotPos - dotPos1;
    let diff2 = dotPos - dotPos2;
    if (diff1 > 0) {
        for (let i = 0; i < diff1; i++) {
            arr1.unshift("0");
        }
    }
    if (diff2 > 0) {
        for (let i = 0; i < diff2; i++) {
            arr2.unshift("0");
        }
    }

    const len1 = arr1.length;
    const len2 = arr2.length;
    const len = Math.max(len1, len2);
    diff1 = len - len1;
    diff2 = len - len2;
    if (diff1 > 0) {
        for (let i = 0; i < diff1; i++) {
            arr1.push("0");
        }
    }
    if (diff2 > 0) {
        for (let i = 0; i < diff2; i++) {
            arr2.push("0");
        }
    }

    const arr = [];
    let sum = 0,
        val1 = 0,
        val2 = 0;
    for (let i = len - 1; i >= 0; i--) {
        if (arr1[i] == '.') {
            arr.unshift('.');
            continue;
        }
        sum = parseInt(arr1[i]) + parseInt(arr2[i]) + val1;
        val1 = sum >= 10 ? 1 : 0;
        val2 = sum >= 10 ? sum - 10 : sum;
        arr.unshift(val2.toString());
    }
    if (val1 == 1) {
        arr.unshift('1');
    }
    return parseFloat(arr.join(''));
}

const num1 = 7.3333333;
const num2 = 4.44444444444;
console.log(addDecimalNumbers(num1, num2));

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

Dropdown menu featuring a customizable input field

Is it possible to have a drop-down list with an input textbox field for creating new items in the same dropdown menu? ...

A dynamic 3-column layout featuring a fluid design, with the middle div expanding based on the

Sorry for the vague title, I'm struggling to explain my issue clearly, so let me elaborate. I am using flexbox to create a 3-column layout and want the middle column to expand when either or both of the side panels are collapsed. Here is a screenshot ...

Display the closing tag depending on specific conditions to simulate the behavior of a calendar

Is it possible to conditionally render a closing tag using v-if? If so, what is the correct way to do it? Initially, I tried the following: <template v-for="day in days"> <td class="days">{{day.number}}</td> <template v-if ...

Displaying MySQL information on an EJS document including references to other tables

Check out the project on GitHub I am currently working on retrieving quiz answers from a MySQL database and displaying them in a form using EJS templating within a node.js/express application. However, I am facing challenges with correctly mapping answers ...

Blackberry Browser 4.2 experiencing spacing troubles

Seeking advice for developing a web application specifically for the Blackberry Browser 4.2. Looking to add vertical spacing between a series of links, but struggling due to lack of support for padding and margin in this version. Have tried using height an ...

Running a continuous JQuery function loop

I need assistance with creating a continuous image fade in and out effect. Currently, my code looks like this: $(document).ready(function(){ $(".slider#1").delay(1000).fadeIn(2000); $(".slider#1").delay(1000).fadeOut(2000); $(".sli ...

Positioning bar chart columns and text using CSS

My component generates HTML for a simple bar chart, with the height and background color computed within the component. Everything functions correctly, but I am facing an issue where long text causes displacement of the bar above it. Another problem is th ...

What's the best way to transform createHmac function from Node.js to C#?

Here's a snippet of code in Node.js: const crypto = require('crypto') const token = crypto.createHmac('sha1', 'value'+'secretValue').update('value').digest('hex'); I am trying to convert t ...

Customize Bootstrap 5: Changing the default color scheme

Currently, I am utilizing Bootstrap 5 (v5.2.1) along with a form on my website. I am attempting to customize the default styles for form validation. Specifically, I want to modify the colored 'tick' or 'check' icon that is displayed wh ...

Platform designed to simplify integration of high-definition imagery and scalable vector illustrations on websites

In the ever-evolving world of technology, some clients support advanced features like svg while others do not. With the rise of high resolution devices such as iPhone 4+ and iPad 3rd gen., it has become crucial to deliver graphics that can meet these stand ...

Doesn't IE support the use of jQuery.last()?

Here is the code snippet I am currently using: $('script').last().parent().html('kkkk') Unfortunately, I am encountering an error in Internet Explorer when running this code. Any suggestions on how to address this issue would be great ...

React native: Implementing a method to trigger an action upon entering a screen

Is there a way to trigger an action when a user visits a specific view in my application? I've tried using componentDidMount and componentWillMount but they don't seem to work for this purpose. If I include the action in the render method, it ca ...

Hide multiple divs with similar ids in JQuery when clicking outside of them

Is there a way to hide all div elements with similar id if none of them are clicked on? Currently, my code only works for the first div because I am using index[0] to retrieve the id. How can I make it work for all ids? Below is the code snippet: $(win ...

Tips on sending multiple values to AngularJS Directive

Currently, I am in the process of creating a simple AngularJS directive. As I am still very new to AngularJS, I would appreciate it if the answers provided could be simplified! The directive I am working on is essentially a combobox. For those unfamiliar ...

Black and white emoji display on Windows 7 using Chrome and Edge browsers

To enhance the visual appeal of my website, I incorporate emojis using Emoji Unicode from https://www.w3schools.com/charsets/ref_emoji.asp. It has come to my notice that on Android, Mac, and iPhone devices, users see colored emoticons while those on Window ...

Display subpages of WordPress site in a dropdown menu on the navigation bar

Currently in the process of converting an HTML website to Wordpress, I am encountering a challenge. The issue lies in my attempt to add a drop-down feature to the navigation list using the wp_list_pages tag. As it stands, when hovering over the "products" ...

Preloading videos for optimal performance on mobile devices

Looking for a solution where 4 MP4/video files, each 5MB in size, can be played consecutively without gaps between them on all browsers and devices. Preferably not looking for a solution involving the replacement of video source files. The current approac ...

Tips for effectively invoking functions upon a page being loaded?

I am currently working on adding pagination feature to manage the number of quotes displayed in my Vue.Js application. I have created a function that divides the quotes based on the paginationLimit value. However, I am encountering an issue where the updat ...

Unable to create a new collection in Firebase Firestore

I encountered an issue while trying to add a collection in Firebase Firestore using the function .collection(doc).set. Despite finding the new user in authentication in Firebase, the collection was not created and the console displayed an error message. ...

Tips for Saving JSON Response from Fetch API into a JavaScript Object

I am facing an issue trying to store a Fetch API JSON as a JavaScript object in order to use it elsewhere. The console.log test is successful, however I am unable to access the data. The Following Works: It displays console entries with three to-do items: ...