欢迎来到资源库(www.zyku.net)

JavaScript

当前位置:首页 > 网页制作 > JavaScript > 数字类型

JS转换成数字类型Number()

时间:2021-06-22|栏目:JavaScript|点击:|我要投稿

JavaScript与许多其他编程语言不同,JavaScript 不会定义不同类型的数,比如整数、短的、长的、浮点的等等。

在JS中浮点的算数,个人实际测试了几个,0.1+0.2,0.4+0.2,0.7+0.2,这种计算的数值就是不是很准确。

字符串转换成数字类型的方法1:Number(需要转换的字符串)

可以通过每个数乘以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>

图示:

(资源库 www.zyku.net)

原文链接:https://www.cnblogs.com/huaxie/p/11720393.html

上一篇:JS四舍五入保留两位小数的方法

栏    目:JavaScript

下一篇:JS截取字符串,去掉前几位,保留后几位

本文标题:JS转换成数字类型Number()

本文地址:https://www.zyku.net/js/2242.html

关于我们 | 版权申明 | 寻求合作 |

重要申明:本站所有的文章、图片、评论等内容,均由网友发表或上传并维护或收集自网络,仅供个人学习交流使用,版权归原作者所有。

如有侵犯您的版权,请与我们联系,我们将在24小时内进行处理、任何非本站因素导致的法律后果,本站均不负任何责任。

联系QQ:95148658 | 邮箱:mb8#qq.com(#换成@)

苏ICP备2020066115号-1

本网站由提供CDN加速/云存储服务