javascript 小数类型格式化

jackxiang 2015-5-12 10:52 | |
背景:做温控,存在小数位数设置到整数时,没有小数后一位,需要补齐,于是格式化势在必行,像c有sprintf,javascript还不清楚,于是查了下,也有类似的函数来实现这样的功能:i1.toFixed(1),也就是:$("#controlTempValue").html(toFixed(setTempRature,1));。
——————————————————————————————————————————————————————————


如果出现:ToFixed() Is Not A Function?
TypeError: setTempRature.toFixed is not a function  
var setTempRatureDisplay = setTempRature.toFixed(1);
使用toFixed对小数四舍五入的时候,弹出以下错误提示:

toFixed() is not a function
后来还是在stackoverflow上找到了答案

toFixed isn’t a property of non-numeric variable types. In other words, Low and High can’t be fixed because when you get the value of something in Javascript, it automatically is set to a string type. Using parseFloat() (or parseInt() with a radix, if it’s an integer) will allow you to convert different variable types to numbers which will enable the toFixed() function to work.
var Low = parseFloat($SliderValFrom.val()),
var High = parseFloat($SliderValTo.val());
原来toFixed只能针对数字类型才能使用,所以对于字符类型的要用parseFloat或者parseInt函数先转一下再调用
摘自:http://www.jason-z.com/tofixed-is-not-a-function/
——————————————————————————————————————————————————————————
在客户js中,我们时常会碰到处理这样的小数类型(转换为字符串):

var i = 1234.8700

document.write("i")  //结果:1234.87   我们想要的结果是1234.8700

也就是小数的有效位数为4位.js中有一个处理这种情况的函数,toFixed(小数有效位数).

如:

var i1 = 3456.244280;
alert(i1.toFixed(2)); // 输出 1024.24

var i2 = 3456.24558;
alert(i2.toFixed(2)); // 输出 1024.25

var i3 = 3456.2;
alert(i3.toFixed(2)); // 输出 1024.20

摘自:http://www.cnblogs.com/rainnight/archive/2009/02/10/1387483.html

作者:jackxiang@向东博客 专注WEB应用 构架之美 --- 构架之美,在于尽态极妍 | 应用之美,在于药到病除
地址:http://jackxiang.com/post/8038/
版权所有。转载时必须以链接形式注明作者和原始出处及本声明!


最后编辑: jackxiang 编辑于2015-5-12 11:04
评论列表
发表评论

昵称

网址

电邮

打开HTML 打开UBB 打开表情 隐藏 记住我 [登入] [注册]