Home  >  Article  >  Web Front-end  >  javascript小数四舍五入多种方法实现_基础知识

javascript小数四舍五入多种方法实现_基础知识

WBOY
WBOYOriginal
2016-05-16 17:45:461039browse

用Javascript取float型小数点后两位,例22.127456取成22.13,如何做?
1. 最笨的办法

复制代码 代码如下:

function get()
{
var s = 22.127456 + "";
var str = s.substring(0,s.indexOf(".") + 3);
alert(str);
}

2. 正则表达式效果不错
复制代码 代码如下:



3. 他就比较聪明了.....
复制代码 代码如下:

<script> <BR>var num=22.127456; <BR>alert( Math.round(num*100)/100); <BR></script>

4.会用新鲜东西的朋友....... 但是需要 IE5.5+才支持。
复制代码 代码如下:

<script> <BR>var num=22.127456; <BR>alert( num.toFixed(2)); <BR></script>
Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn