Javascript Addition wont work

2019-01-29 13:58发布

问题:

can anybody tell me how to add up these variables:

var preciopag = document.valores.T1.value;

var libras = document.valores.T2.value;

var serviciocom = 5.00

var contador1 = 0;

var contador2 = 0;

var tramite = 0;

var enviopty = 0;

var ITBMS = 0;

var Total = preciopag + serviciocom + enviopty + tramite + ITBMS;

Thanks in advance.

回答1:

The value of elements is always a string, so + will result in concatenation, not addition.

Convert from string to number when retrieving the values:

var preciopag = +document.valores.T1.value;
var libras = +document.valores.T2.value;

There I've used +, which will look at the entire string, but you might look at parseFloat which will ignore anything invalid at the end; it depends entirely on what you want to do with semi-valid input.

Demonstration:

var preciopag = "5";   // Simulating document.valores.T1.value
var libras = "10";     // Simulating document.valores.T2.value
var serviciocom = 5.00
var contador1 = 0;
var contador2 = 0;
var tramite = 0;
var enviopty = 0;
var ITBMS = 0;
var Total = preciopag + serviciocom + enviopty + tramite + ITBMS;

snippet.log(Total); // "55000" - wrong

// Instead:
preciopag = +"5";    // Simulating document.valores.T1.value 
libras = +"10";      // Simulating document.valores.T2.value
Total = preciopag + serviciocom + enviopty + tramite + ITBMS;

snippet.log(Total); // "10" - right
<!-- Script provides the `snippet` object, see http://meta.stackexchange.com/a/242144/134069 -->
<script src="http://tjcrowder.github.io/simple-snippets-console/snippet.js"></script>