我想添加一个变量值,但结果编号显示为字符串

时间:2016-12-20 18:36:15

标签: javascript

我想添加温度的结果和x变量的结果,但这是不可能的,因为var cTemp是一个字符串。

以下是代码:

//Temperature from Puebla
var cTemp;
var dTemp;

var outside = $.getJSON("http://ip-api.com/json", function(data2){
    lat = data2.lat;
    long = data2.lon;
    var api='http://api.openweathermap.org/data/2.5/weather?lat=' + lat    + '&lon=' + long + '&appid=cd380bb8125ea7190ceb6ca01bc0f681';

    $.getJSON(api, function(data){
        var kelvin = data.main.temp;
        cTemp = (kelvin - 273).toFixed(1);
        $(".pueblatemp").html(cTemp);
    });
});

var a = cTemp;
var b = x;

var total = a + b;

$('.difference').html(total + "C");

3 个答案:

答案 0 :(得分:0)

调用toFixed()将返回一个字符串。将cTemp作为一个数字,直到你显示它将解决这个问题。



$.getJSON(api, function(data){
        var kelvin = data.main.temp;
        cTemp = kelvin - 273;
        $(".pueblatemp").html(cTemp.toFixed(2));
    });






$('.difference').html(total.toFixed(2) + "C");




答案 1 :(得分:0)

这会让你更接近你需要做的事情

//Temperature from Puebla
    var cTemp;
    var dTemp;

var outside = $.getJSON("http://ip-api.com/json", function(data2){
    lat = data2.lat;
    long = data2.lon;
    var api='http://api.openweathermap.org/data/2.5/weather?lat=' + lat    + '&lon=' + long + '&appid=cd380bb8125ea7190ceb6ca01bc0f681';

    $.getJSON(api, function(data){
        var kelvin = data.main.temp;
        cTemp = (Number(kelvin) - Number(273)).toFixed(1);
        $(".pueblatemp").html(cTemp);

        var a = cTemp;
        var b = x;    //what is x???

        var total = Number(a) + Number(b);

        $('.difference').html(total + "C");

    });
});

console.log("This will run before $.getJSON finishes!!!");

答案 2 :(得分:0)

使用parseIntparseFloat

 var aStringNumber = "1";
 var anotherStringNumber = "2";
 console.log(aStringNumber + anotherStringNumber); //"12"
 console.log(parseInt(aStringNumber) + parseInt(anotherStringNumber)); //3