0

我的问题是要在 jquery 中浮动数字。我在这个网站上查看了其他关于它的问题,但我找不到我看的那个。

在我的部分代码中,我使用$.post了 jquery。我向数据库发送请求并以json格式获取数据。在我的数据库中,一些数字的格式类似于 345,54565000000。所以,我想在逗号后浮动 5 位数字。

我的部分代码是:

$.post("http://localhost/ajax.php",
      function(data) {
          var listdata;
          $.each(data, function(i,item){

              listdata += "<td>"+item.number+"</td>";

          });

            $(".result).empty().html(listdata);

    },"json"
);

我的一些试验是这样的:(这是行不通的)

1.)

var number = (item.number).toFixed(5);
listdata += "<td>"+number+"</td>"; 

2.)

var number=item.number;
var new_number = number.toFixed(5);
listdata += "<td>"+new_number+"</td>"; 

谢谢您的回复。

4

4 回答 4

2
var number = 345.54565000000​;

var parsedNumber = parseFloat(parseInt(number*100000,10)/100000);

小提琴;

如果该分隔符实际上是逗号,则必须将其替换为.replace(',', '.')

于 2012-12-08T23:56:05.290 回答
1

我使用这个功能:

function roundNumber(number,decimals) {
    var newString;// The new rounded number
    decimals = Number(decimals);
    if (decimals < 1) {
        newString = (Math.round(number)).toString();
    } else {
        var numString = number.toString();
        if (numString.lastIndexOf(".") == -1) {// If there is no decimal point
            numString += ".";// give it one at the end
        }
        var cutoff = numString.lastIndexOf(".") + decimals;// The point at which to truncate the number
        var d1 = Number(numString.substring(cutoff,cutoff+1));// The value of the last decimal place that we'll end up with
        var d2 = Number(numString.substring(cutoff+1,cutoff+2));// The next decimal, after the last one we want
        if (d2 >= 5) {// Do we need to round up at all? If not, the string will just be truncated
            if (d1 == 9 && cutoff > 0) {// If the last digit is 9, find a new cutoff point
                while (cutoff > 0 && (d1 == 9 || isNaN(d1))) {
                    if (d1 != ".") {
                        cutoff -= 1;
                        d1 = Number(numString.substring(cutoff,cutoff+1));
                    } else {
                        cutoff -= 1;
                    }
                }
            }
            d1 += 1;
        } 
        newString = numString.substring(0,cutoff) + d1.toString();
    }
    if (newString.lastIndexOf(".") == -1) {// Do this again, to the new string
        newString += ".";
    }
    var decs = (newString.substring(newString.lastIndexOf(".")+1)).length;
    for(var i=0;i<decimals-decs;i++) newString += "0";
    return newString;
}

因此,在您的代码中,将第 6 行更改为:

listdata += "<td>"+ roundNumber(item.number, 5) +"</td>";
于 2012-12-08T23:48:59.607 回答
1

我假设你有逗号,并且你想坚持使用逗号,这样会破坏任何与 Float 相关的功能,所以......快速而肮脏,但可以完成工作:

代替

listdata += "<td>"+item.number+"</td>";

listdata += "<td>"+parseFloat(item.number.replace(',', '.')).toFixed(5).replace('.', ',')+"</td>";
于 2012-12-08T23:56:52.777 回答
1

我发现的禁食方式是

((number * Math.pow(10, numberOfDigits)) | 0) / Math.pow(10, numberOfDigits)

编辑:忘记了 Math.pow,这很重要。

于 2012-12-09T00:05:37.607 回答