Home > Web Front-end > JS Tutorial > body text

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

WBOY
Release: 2016-05-16 17:45:46
Original
1043 people have browsed it

用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>
Related labels:
source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!