首页 > 解决方案 > 如何限制 JavaScript API 请求小数位数

问题描述

我正在使用下面的代码从 api 获取一些数据。响应将始终是一个数字,但是我想在输出时将小数位数限制为 2。

  $(document).ready(function sendRequest() {
        $.ajax({
          url: 'https://apiurl',
          type: 'GET',
          success: function(response) {
            $("#test").html(response);
          },
          error: function() {
            $('#errors').text("Error");
          }
        });
    });

我尝试了以下方法,但这不起作用。

$("#test").html(response.toFixed(2) 

有任何想法吗?

标签: javascriptjquery

解决方案


您的响应变量是字符串,您需要先转换变量

var res = parseFloat(response) ;

$("#test").html(res.toFixed(2)) ;

推荐阅读