简体   繁体   English

难以将JSON对象的值四舍五入到Javascript中的小数点后两位

[英]Difficulty rounding up json object value to two decimal place in Javascript

I am having difficulty converting val.distance to a round figure. 我很难将val.distance转换为圆形。

the value passed from the server for val.distance is 197.13572611205996. 从服务器传递的val.distance值为197.13572611205996。 what i want to do is to round it to 197.13 or 197.14. 我想做的是将其四舍五入到197.13或197.14。 before outputting it. 在输出之前。 If I run this it breaks the code, however when i run it without trying to round the figure it works. 如果我运行它会破坏代码,但是当我运行它而不尝试四舍五入时它会工作。

 $.getJSON('http://localhost/locategas/pas-autofind.php?lat='+poslat+'&lon='+poslon+'&jsoncallback=?', function (data) {

 var output='<ul data-role="listview" data-filter="true">';

$.each(data.david, function(key,val){

var MYDISTANCE = math.round(val.distance); 

output+='<li>';
    output += '<a href="#detailPage" onclick="showPost(' + val.stationId + ')">';
    output+='<h3>' + val.stationName + '</h3>';
    output+='<p>' + val.region + '</p>';
    output+='<p>' + val.city + '</p>';
    output+='<p>' + val.town + '</p>';
    output+='<p>' + val.email + '</p>';
    output+='<p>' + val.tel1 + '</p>';
    output+='<p>' + val.tel2 + '</p>';
    output+='<p>' + val.status + '</p>';
    output+='<p>' + MYDISTANCE  + '</p>';
    output+='</a>';
    output+='</li>';
}); // go through each post
output+='</ul>';
$('#ul-li-items').html(output);
$('#ul-li-items').trigger('create');
// lists all the posts   
 });

Any help would be greatly appreciated, thanks. 任何帮助将不胜感激,谢谢。

(Number(8.2342342)).toFixed(2)

Edit: Purpose was casting therefore only Number() is required and not new Number() 编辑:目的是强制转换,因此只需要Number()而不是新的Number()

reference: new Number() vs Number() 参考: new Number()vs Number()

It's hard to tell without seeing your error message, but I imagine that 很难看到错误消息,但是我想那是

math.round(…)

should be 应该

Math.round(…)

But this is only the first part of your problem, because Math.round will round to an integer, not to 2 decimal places. 但这只是问题的第一部分,因为Math.round将舍入为整数,而不是小数点后2位。

galchen's answer is a simpler way to achieve what you're trying to do. galchen的答案是实现您要完成的操作的更简单方法。

Why don't you do something like" 你为什么不做类似的事情?

var value=123.123456;
value=value.toFixed(2);

This should give you the value 123.12. 这应该为您提供值123.12。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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