Errol28Rose
Errol28Rose

Reputation: 81

Convert string to with two decimals and then add both

I have two variables which are string and I convert them to float. But when I want to add both and get a result, they both get concatenated.

This is how I do it:

    <!DOCTYPE html>
    <html>
    <body>
    <p id="demo"></p>
    
    <script>
    var CantVendida='2.00';
    var CantidadBonificacion='1.00';
    var CantidadVenBon=parseFloat(CantVendida).toFixed(2)+parseFloat(CantidadBonificacion).toFixed(2);
    document.getElementById("demo").innerHTML = CantidadVenBon;
    </script>
    
    </body>
    </html>

Upvotes: 0

Views: 41

Answers (2)

M. &#199;ağlar TUFAN
M. &#199;ağlar TUFAN

Reputation: 910

This question is about type conversions.

This page shows how to converting data types.

In your question, we need to use Number() built in function to convert String to Number.

let stringNumberOne = "2.3"; // typeof(stringNumberOne) => "string"
let stringNumberTwo = "3.3"; // typeof(stringNumberTwo) => "string"
let stringAddition = stringNumberOne + stringNumberTwo; // Result: "2.33.3"

let convertedStringNumberOne = Number(stringNumberOne); // typeof(convertedStringNumberOne) => "number"
let convertedStringNumberTwo = Number(stringNumberTwo); // typeof(convertedStringNumberTwo) => "number"
let convertedStringAddition = convertedStringNumberOne + convertedStringNumberTwo; // Result: 5.6

Upvotes: 1

Marc
Marc

Reputation: 11613

Use .toFixed(2) on the result rather than the operands.

If you use .toFixed(2) on the operands, you're actually converting them to strings before the + operation takes place. That's why you're getting string concatenation instead of mathematical addition in your version.

See below.

    <!DOCTYPE html>
    <html>
    <body>
    <p id="demo"></p>
    
    <script>
    var CantVendida='2.00';
    var CantidadBonificacion='1.00';
    var CantidadVenBon=parseFloat(CantVendida)+parseFloat(CantidadBonificacion);
    document.getElementById("demo").innerHTML = CantidadVenBon.toFixed(2);
    </script>
    
    </body>
    </html>

Upvotes: 4

Related Questions