使用 JavaScript 获取数字的小数部分

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/4512306/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 12:43:59  来源:igfitidea点击:

Get decimal portion of a number with JavaScript

javascriptfloating-pointnumbersdecimalrounding

提问by Oscar

I have float numbers like 3.2and 1.6.

我有像3.2和这样的浮点数1.6

I need to separate the number into the integer and decimal part. For example, a value of 3.2would be split into two numbers, i.e. 3and 0.2

我需要将数字分成整数和小数部分。例如,一个值3.2将被分成两个数字,即30.2

Getting the integer portion is easy:

获取整数部分很容易:

n = Math.floor(n);

But I am having trouble getting the decimal portion. I have tried this:

但是我在获取小数部分时遇到问题。我试过这个:

remainer = n % 2; //obtem a parte decimal do rating

But it does not always work correctly.

但它并不总是能正常工作。

The previous code has the following output:

前面的代码具有以下输出:

n = 3.1 => remainer = 1.1

What I am missing here?

我在这里缺少什么?

回答by Ignacio Vazquez-Abrams

Use 1, not 2.

使用1,不是2

js> 2.3 % 1
0.2999999999999998

回答by greenimpala

var decimal = n - Math.floor(n)

Although this won't work for minus numbers so we might have to do

虽然这对负数不起作用,所以我们可能不得不这样做

n = Math.abs(n); // Change to positive
var decimal = n - Math.floor(n)

回答by sdleihssirhc

You could convert to string, right?

你可以转换成字符串,对吧?

n = (n + "").split(".");

回答by jomofrodo

How is 0.2999999999999998 an acceptable answer? If I were the asker I would want an answer of .3. What we have here is false precision, and my experiments with floor, %, etc indicate that Javascript is fond of false precision for these operations. So I think the answers that are using conversion to string are on the right track.

0.2999999999999998 如何是可接受的答案?如果我是提问者,我希望得到 0.3 的答案。我们这里有的是错误精度,我对 floor、% 等的实验表明 Javascript 喜欢这些操作的错误精度。所以我认为使用转换为字符串的答案是正确的。

I would do this:

我会这样做:

var decPart = (n+"").split(".")[1];

Specifically, I was using 100233.1 and I wanted the answer ".1".

具体来说,我使用的是 100233.1,我想要答案“.1”。

回答by Zantafio

Here's how I do it, which I think is the most straightforward way to do it:

这是我的做法,我认为这是最直接的方法:

var x = 3.2;
int_part = Math.trunc(x); // returns 3
float_part = Number((x-int_part).toFixed(2)); // return 0.2

回答by Ethan

A simple way of doing it is:

一个简单的方法是:

var x = 3.2;
var decimals = x - Math.floor(x);
console.log(decimals); //Returns 0.20000000000000018

Unfortunately, that doesn't return the exact value. However, that is easily fixed:

不幸的是,这不会返回确切的值。但是,这很容易解决:

var x = 3.2;
var decimals = x - Math.floor(x);
console.log(decimals.toFixed(1)); //Returns 0.2

You can use this if you don't know the number of decimal places:

如果您不知道小数位数,您可以使用它:

var x = 3.2;
var decimals = x - Math.floor(x);

var decimalPlaces = x.toString().split('.')[1].length;
decimals = decimals.toFixed(decimalPlaces);

console.log(decimals); //Returns 0.2

回答by Nurlan

Language independent way:

语言独立方式:

var a = 3.2;
var fract = a * 10 % 10 /10; //0.2
var integr = a - fract; //3

note that it correct only for numbers with one fractioanal lenght )

请注意,它仅适用于具有一个小数长度的数字)

回答by Sheki

You can use parseInt()function to get the integer part than use that to extract the decimal part

您可以使用parseInt()函数来获取整数部分而不是使用它来提取小数部分

var myNumber = 3.2;
var integerPart = parseInt(myNumber);
var decimalPart = myNumber - integerPart;

Or you could use regex like:

或者你可以使用正则表达式,如:

splitFloat = function(n){
   const regex = /(\d*)[.,]{1}(\d*)/;
   var m;

   if ((m = regex.exec(n.toString())) !== null) {
       return {
          integer:parseInt(m[1]),
          decimal:parseFloat(`0.${m[2]}`)
       }
   }
}

回答by Gabriel Hautclocq

If precision matters and you require consistent results, here are a few propositions that will return the decimal part of any number as a string, including the leading "0.". If you need it as a float, just add var f = parseFloat( result )in the end.

如果精度很重要并且您需要一致的结果,这里有一些命题可以将任何数字的小数部分作为字符串返回,包括前导“0.”。如果您需要它作为浮点数,只需var f = parseFloat( result )在最后添加。

If the decimal part equals zero, "0.0" will be returned. Null, NaN and undefined numbers are not tested.

如果小数部分为零,则返回“0.0”。不测试 Null、NaN 和未定义的数字。

1. String.split

1. 字符串分割

var nstring = (n + ""),
    narray  = nstring.split("."),
    result  = "0." + ( narray.length > 1 ? narray[1] : "0" );

2. String.substring, String.indexOf

2. String.substring, String.indexOf

var nstring = (n + ""),
    nindex  = nstring.indexOf("."),
    result  = "0." + (nindex > -1 ? nstring.substring(nindex + 1) : "0");

3. Math.floor, Number.toFixed, String.indexOf

3. Math.floor, Number.toFixed, String.indexOf

var nstring = (n + ""),
    nindex  = nstring.indexOf("."),
    result  = ( nindex > -1 ? (n - Math.floor(n)).toFixed(nstring.length - nindex - 1) : "0.0");

4. Math.floor, Number.toFixed, String.split

4. Math.floor, Number.toFixed, String.split

var nstring = (n + ""),
    narray  = nstring.split("."),
    result  = (narray.length > 1 ? (n - Math.floor(n)).toFixed(narray[1].length) : "0.0");

Here is a jsPerf link: https://jsperf.com/decpart-of-number/

这是一个 jsPerf 链接:https://jsperf.com/decpart-of-number/

We can see that proposition #2 is the fastest.

我们可以看到命题#2 是最快的。

回答by cdmdotnet

The following works regardless of the regional settings for decimal separator... on the condition only one character is used for a separator.

无论小数点分隔符的区域设置如何,以下都有效......条件是仅使用一个字符作为分隔符。

var n = 2015.15;
var integer = Math.floor(n).toString();
var strungNumber = n.toString();
if (integer.length === strungNumber.length)
  return "0";
return strungNumber.substring(integer.length + 1);

It ain't pretty, but it's accurate.

它不漂亮,但它是准确的。