Home >Web Front-end >JS Tutorial >How to remove two decimal places in javascript

How to remove two decimal places in javascript

青灯夜游
青灯夜游Original
2022-02-15 18:51:244368browse

方法:1、使用“数值字符串对象.substring(0,数值字符串对象.indexOf(".")+3)”语句;2、使用“Math.round(数值对象*100)/100”语句;3、使用“数值对象.toFixed(2)”语句。

How to remove two decimal places in javascript

本教程操作环境:windows7系统、javascript1.8.5版、Dell G3电脑。

javascript怎么去掉小数点后两位?例22.123456取成22.12要如何做?

1、通过substring截取

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

How to remove two decimal places in javascript

2、正则表达式

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

3、数据类型保留上

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

4、toFixed方法

var num=22.123456;
alert(num.toFixed(2));

【相关推荐:javascript学习教程

The above is the detailed content of How to remove two decimal places in javascript. For more information, please follow other related articles on the PHP Chinese website!

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