如何在 JavaScript 中对数字进行四舍五入? [英] How do I round a number in JavaScript?

查看:14
本文介绍了如何在 JavaScript 中对数字进行四舍五入?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在做一个项目时,我遇到了一个由前雇员创建的 JS 脚本,它基本上以以下形式创建报告

While working on a project, I came across a JS-script created by a former employee that basically creates a report in the form of

Name : Value
Name2 : Value2

等等

问题是这些值有时可以是浮点数(具有不同的精度)、整数,甚至是 2.20011E+17 的形式.我要输出的是纯整数.不过,我不太了解 JavaScript.我将如何编写一个方法来获取这些有时浮点数并使其成为整数?

The peoblem is that the values can sometimes be floats (with different precision), integers, or even in the form 2.20011E+17. What I want to output are pure integers. I don't know a lot of JavaScript, though. How would I go about writing a method that takes these sometimes-floats and makes them integers?

推荐答案

您必须将输入转换为数字,然后将它们四舍五入:

You hav to convert your input into a number and then round them:

function toInteger(number){ 
  return Math.round(  // round to nearest integer
    Number(number)    // type cast your input
  ); 
};

或作为一个班轮:

function toInt(n){ return Math.round(Number(n)); };

使用不同的值进行测试:

Testing with different values:

toInteger(2.5);           // 3
toInteger(1000);          // 1000
toInteger("12345.12345"); // 12345
toInteger("2.20011E+17"); // 220011000000000000

这篇关于如何在 JavaScript 中对数字进行四舍五入?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆