Home > Web Front-end > JS Tutorial > Tutorial on how to get two decimal places in js

Tutorial on how to get two decimal places in js

小云云
Release: 2017-12-13 15:14:11
Original
2591 people have browsed it

本文主要和大家分享js如何取小数点后两位方法,Javascript取float型小数点后两位,例22.123456取成22.12,如何做?

1.通过substring截取。


  1. function getnum()  
    {  
    var num = 22.123456;  
    var result = num.substring(0,s.indexOf(".")+3);  
    alert(result);  
    }
    Copy after login

2. 正则表达式。


  1. function getnum()  
    {  
    var num = 22.123456;  
    var aNew;  
    var re = /([0-9]+\.[0-9]{2})[0-9]*/;  
    aNew = num.replace(re,"$1");  
    alert(aNew);  
    }
    Copy after login


3.数据类型保留上。

  1. function getnum()  
    {  
    var num=22.123456;  
    alert( Math.round(num*100)/100);  
    }
    Copy after login

4.toFixed方法


  1. alert(num.toFixed(2));
    Copy after login


相关推荐:

总结javascript获取小数点后几位方法

mysql截取小数点后1位_MySQL

几种取小数点后几位的方法实例 javascript

The above is the detailed content of Tutorial on how to get two decimal places in js. For more information, please follow other related articles on the PHP Chinese website!

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