Uzyskaj dziesiętną część liczby za pomocą JavaScript

Mam takie liczby float jak 3.2 i 1.6.

Muszę rozdzielić liczbę na liczbę całkowitą i dziesiętną. Na przykład wartość 3.2 zostanie podzielona na dwie liczby, tj. 3 i 0.2

Uzyskanie części całkowitej jest łatwe:

n = Math.floor(n);

Ale mam problem z uzyskaniem części dziesiętnej. Próbowałem tego:

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

Ale nie zawsze działa poprawnie.

Poprzedni kod ma następujące wyjście:

n = 3.1 => remainer = 1.1

Czego mi brakuje tutaj?

Author: alex, 2010-12-22

16 answers

Użyj 1, nie 2.

js> 2.3 % 1
0.2999999999999998
 277
Author: Ignacio Vazquez-Abrams,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2010-12-22 18:21:54
var decimal = n - Math.floor(n)

Chociaż to nie zadziała dla liczb ujemnych, więc może będziemy musieli zrobić

n = Math.abs(n); // Change to positive
var decimal = n - Math.floor(n)
 72
Author: greenimpala,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2010-12-22 18:22:54

Można przekonwertować na string, prawda?

n = (n + "").split(".");
 53
Author: sdleihssirhc,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2010-12-22 20:01:49

W Jaki Sposób 0.2999999999999999998 jest akceptowalną odpowiedzią? Gdybym był pytającym, prosiłbym o odpowiedź .3. To, co tu mamy, to fałszywa precyzja, a moje eksperymenty z podłogą, % itp. wskazują, że Javascript lubi fałszywą precyzję dla tych operacji. Więc myślę, że odpowiedzi, które używają konwersji do Ciągu są na dobrej drodze.

Zrobiłbym to:

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

Konkretnie, używałem 100233.1 i chciałem odpowiedzi".1".

 23
Author: jomofrodo,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2014-04-02 14:04:56

Prosty sposób to:

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

Niestety, to nie zwraca dokładnej wartości. Jednak łatwo to naprawić:

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

Możesz użyć tego, jeśli nie znasz liczby miejsc po przecinku:

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
 9
Author: Ethan,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2016-12-02 03:52:14

Oto Jak to robię, co myślę, że jest najprostszym sposobem, aby to zrobić:

var x = 3.2;
int_part = Math.trunc(x); // returns 3
float_part = Number((x-int_part).toFixed(2)); // return 0.2
 9
Author: Zantafio,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2017-03-04 12:11:21

Poniższe działanie działa niezależnie od ustawień regionalnych dla separatora dziesiętnego... pod warunkiem, że separator jest używany tylko jeden znak.

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);
Nie jest ładna, ale dokładna.
 5
Author: cdmdotnet,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2015-06-17 23:17:51

Możesz przekonwertować go na łańcuch znaków i użyć metody replace, Aby zastąpić część całkowitą z zero, a następnie przekonwertować wynik z powrotem na liczbę:

var number = 123.123812,
    decimals = +number.toString().replace(/^[^\.]+/,'0');
 4
Author: gion_13,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2013-03-27 20:57:56

W zależności od użycia podasz później, ale to proste rozwiązanie może również pomóc.

Nie mówię, że to dobre rozwiązanie, ale w niektórych konkretnych przypadkach działa.]}
var a = 10.2
var c = a.toString().split(".")
console.log(c[1] == 2) //True
console.log(c[1] === 2)  //False

Ale zajmie to dłużej niż proponowane rozwiązanie przez @ Brian M. Hunt

(2.3 % 1).toFixed(4)
 4
Author: David Sánchez,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2014-07-24 08:19:45

Język niezależny sposób:

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

Zauważ, że poprawne jest tylko dla liczb o jednej długości fraktalnej)

 3
Author: Nurlan,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2016-01-22 10:35:21

Jeśli precyzja ma znaczenie i potrzebujesz spójnych wyników, oto kilka propozycji, które zwrócą część dziesiętną dowolnej liczby jako ciąg znaków, w tym wiodące " 0.". Jeśli potrzebujesz go jako float, po prostu dodaj var f = parseFloat( result ) na końcu.

Jeśli część dziesiętna jest równa zeru, zostanie zwrócone "0.0". Liczby null, NaN i undefined nie są testowane.

1. / Align = "left" / split

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

2. Sznurek.substring, String.indexOf

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

3. Matematyka.piętro, numer.toFixed, Sznurek.indexOf

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

4. Matematyka.piętro, numer.toFixed, String.split

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

Oto link jsPerf: https://jsperf.com/decpart-of-number/

Widzimy, że propozycja nr 2 jest najszybsza.

 3
Author: Gabriel Hautclocq,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2018-01-17 14:52:14

Możesz użyć funkcji parseInt(), Aby uzyskać część całkowitą, niż użyć jej do wyodrębnienia części dziesiętnej

var myNumber = 3.2;
var integerPart = parseInt(myNumber);
var decimalPart = myNumber - integerPart;
 2
Author: Sheki,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2018-06-18 07:41:45

Miałem przypadek, w którym wiedziałem, że wszystkie liczby będą miały tylko jeden dziesiętny i chciałem uzyskać część dziesiętną jako liczbę całkowitą, więc skończyło się na użyciu tego rodzaju podejścia:

var number = 3.1,
    decimalAsInt = Math.round((number - parseInt(number)) * 10); // returns 1

Działa to dobrze również z liczbami całkowitymi, zwracając w tych przypadkach 0.

 1
Author: walpek,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2016-02-22 12:33:35

Używam:

var n = -556.123444444;
var str = n.toString();
var decimalOnly = 0;

if( str.indexOf('.') != -1 ){ //check if has decimal
    var decimalOnly = parseFloat(Math.abs(n).toString().split('.')[1]);
}

Input: -556.123444444

Wynik: 123444444

 1
Author: DavidDunham,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2017-11-16 10:48:17

Po obejrzeniu kilku z nich, używam teraz...

var rtnValue = Number(7.23);
var tempDec = ((rtnValue / 1) - Math.floor(rtnValue)).toFixed(2);
 0
Author: Patrick,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2016-04-17 17:45:58
float a=3.2;
int b=(int)a; // you'll get output b=3 here;
int c=(int)a-b; // you'll get c=.2 value here
 -9
Author: user2381223,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2013-05-14 10:32:33