简体   繁体   中英

Adding Strings With Float Numbers Javascript

I'm trying to solve a question to be able to add strings that include floating point numbers. For example "110.75" + "9" = "119.75".

I have the code below that I have been wrestling with for about an hour now and could appreciate if anybody could point me in the right direction as to where I might be wrong. I am only returning an empty string "" for every test case I write for myself.

var addStrings = function(num1, num2) {
    const zero = 0;
    let s1 = num1.split(".");
    let s2 = num2.split(".");
    
    result = "";
    
    let sd1 = s1.length > 1 ? s1[1] : zero;
    let sd2 = s2.length > 1 ? s2[1] : zero;
    while(sd1.length !== sd2.length) {
        if(sd1.length < sd2.length) {
            sd1 += zero
        } else {
            sd2 += zero;
        }
    }
    
    let carry = addStringHelper(sd1, sd2, result, 0);
    result.concat(".");
    
    addStringHelper(s1[0], s2[0], result, carry);
    return result.split("").reverse().join("");
};

function addStringHelper(str1, str2, result, carry) {
    let i = str1.length - 1;
    let j = str2.length - 1;
    while(i >= 0 || j >= 0) {
        let sum = carry
        
        if(j >= 0) {
            sum += str1.charAt(j--) - '0';
        }
        if(i >= 0 ) {
            sum += str2.charAt(i--) - '0';
        }
        carry = sum / 10;
        result.concat(sum % 10);
    }
    return carry
}

Convert the strings into Number , add them and then convert them back to String .

 const addStrings = (num1, num2) => String(Number(num1) + Number(num2)) console.log(addStrings("110.67", "9"))

Also, try to handle floating point rounding in some way. You can try using toFixed (this will fix the result to two decimal places) .

 const addStrings = (num1, num2) => String((Number(num1) + Number(num2)).toFixed(2)) console.log(addStrings("0.2", "0.1"))

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM