LOGO OA教程 ERP教程 模切知识交流 PMS教程 CRM教程 开发文档 其他文档  
 
网站管理员

JS中数字直接相加时出错,转换成数字类型Number()或乘10除10解决

admin
2023年9月28日 0:3 本文热度 439

Javascript与许多其他编程语言不同,Javascript 不会定义不同类型的数,比如整数、短的、长的、浮点的等等。
在JS中浮点的算数,个人实际测试了几个,0.1+0.2,0.4+0.2,0.7+0.2,这种计算的数值就是不是很准确,例如,0.4+0.2的结是0.6000000000000001
字符串转换成数字类型的方法如下:

方法1:Number(需要转换的字符串)

方法2:
可以通过每个数乘以10,最后再整体除以10的方法,让这几个有问题的浮点数显示正常。
例如,0.4+0.2的结是0.6000000000000001,而使用(0.4*10+0.2*10)/10,结果就是0.6
测试代码:

<body>
小数测试:
文本框value值获取的是string类型的:
<input type="text" id="A1" value="0.3">+
<input type="text" id="A2" value="0.4">=
<input type="text" id="S1">
<br>
<input type="button" onclick="s1()" value="点击字符串拼接"><br>
<input type="button" onclick="s2()" value="点击Number转换的"><br>
<input type="button" onclick="s3()" value="点击Number转换的且用了乘除法"><br>
<script language="javascript" type="text/javascript">  
function s1(){//文本框输入的为字符串类型,相加后为字符串拼接
   var textA1,textA2,textS1;
   textA1
=document.getElementById("A1").value;
   textA2
=document.getElementById("A2").value;
   textS1
=textA1+textA2;
   document.getElementById(
"S1").value=textS1;
   console.log(
"textA1的类型是:"+typeof(textA1));
   console.log(
"textA2的类型是:"+typeof(textA2));
   console.log(
"textS1的类型是:"+typeof(textS1));
};
function s2(){//字符串类型转换成数字类型,Number(需要转换的字符串)
   var textA1,textA2,textS1;
   textA1
=Number(document.getElementById("A1").value);
   textA2
=Number(document.getElementById("A2").value);
   textS1
=textA1+textA2;
   document.getElementById(
"S1").value=textS1;
   console.log(
"textA1的类型是:"+typeof(textA1));
   console.log(
"textA2的类型是:"+typeof(textA2));
   console.log(
"textS1的类型是:"+typeof(textS1));
   console.log(
0.3+0.4);
   console.log(
0.3+0.3);
   console.log(
0.1+0.2);
   console.log(
0.4+0.2);    
   console.log(
0.7+0.2);
   console.log(
0.6+0.2);
   console.log(
0.44+0.22);
};
function s3(){//用乘除法解决该问题
   var textA1,textA2,textS1;
   textA1
=Number(document.getElementById("A1").value);
   textA2
=Number(document.getElementById("A2").value);
   textS1
=(textA1*10+textA2*10)/10;
   document.getElementById("S1").value=textS1;
   console.log(
0.4+0.2);
   console.log((
0.4*10+0.2*10)/10);
};
</script>
</body>

图示:


该文章在 2023/9/28 0:03:51 编辑过
关键字查询
相关文章
正在查询...
点晴ERP是一款针对中小制造业的专业生产管理软件系统,系统成熟度和易用性得到了国内大量中小企业的青睐。
点晴PMS码头管理系统主要针对港口码头集装箱与散货日常运作、调度、堆场、车队、财务费用、相关报表等业务管理,结合码头的业务特点,围绕调度、堆场作业而开发的。集技术的先进性、管理的有效性于一体,是物流码头及其他港口类企业的高效ERP管理信息系统。
点晴WMS仓储管理系统提供了货物产品管理,销售管理,采购管理,仓储管理,仓库管理,保质期管理,货位管理,库位管理,生产管理,WMS管理系统,标签打印,条形码,二维码管理,批号管理软件。
点晴免费OA是一款软件和通用服务都免费,不限功能、不限时间、不限用户的免费OA协同办公管理系统。
Copyright 2010-2024 ClickSun All Rights Reserved