本文介绍了Javascript toFixed功能的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个关于toFixed()函数的问题。如果我有漂浮物,例如 - 3.123123423 0 。如何使用toFixed(2)将其输出到输入框,以便输入框值为 3.12 0 。我的意思是如果这个值是整数,我想输出它,而不是 .00 :) 在JavaScript中,整数和浮点数之间没有区别,下面是我的quick'n'dirty方法:

  theNumber.toFixed(2 ).replace(。00,); 

或者一般的东西:

  myToFixed = function(n,digits){
digits = digits || 0;
return n.toFixed(digits).replace(new RegExp(\\.0 {+ digits +}),);
}

myToFixed(32.1212,2) - > 32.12
myToFixed(32.1212,0) - > 32
myToFixed(32,2) - > 32
myToFixed(32.1,2) - > 32.10


I have a question regarding toFixed() function. If I have a float e.g. - 3.123123423 and 0. How can I output it to input box with toFixed(2) so the inputbox values would be 3.12 and 0. I mean if the value is integer I want output it without trailing .00 :)

解决方案

As there is no difference between integers and floats in JavaScript, here is my quick'n'dirty approach:

theNumber.toFixed(2).replace(".00", "");

Or something generic:

myToFixed = function (n, digits) {
    digits = digits || 0;
    return n.toFixed(digits).replace(new RegExp("\\.0{" + digits + "}"), "");
}

myToFixed(32.1212, 2) --> "32.12"
myToFixed(32.1212, 0) --> "32"
myToFixed(32, 2) --> "32"
myToFixed(32.1, 2) --> "32.10"

这篇关于Javascript toFixed功能的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-20 13:41