PL
JavaScript - Math.trunc() - przykład metody z dokumentacją
4 points
Math.trunc()
metoda zwraca całkowitą część liczby.
xxxxxxxxxx
1
console.log( Math.trunc( 5 )); // 5
2
console.log( Math.trunc( 3.14 )); // 3
3
console.log( Math.trunc( -3.14 )); // -3
4
console.log( Math.trunc( 0.123 )); // 0
5
console.log( Math.trunc( -0.123 )); // -0
6
7
console.log( Math.trunc( '+3.14' ) ); // 3.14
8
console.log( Math.trunc( '-3.14' ) ); // -3.14
9
console.log( Math.trunc( NaN ) ); // NaN
10
console.log( Math.trunc( 'foo' ) ); // NaN
11
12
console.log( Math.trunc() ); // NaN
Składnia | Math.trunc(number) |
Parametry | number - liczba całkowita lub zmiennoprzecinkowa (typ prosty). |
Wynik |
Całkowita część wartości liczbowej. Jeśli liczba ma wartość Jeśli liczba to Jeśli liczba to |
Opis |
|
Z uwagi na to, że Math.trunc()
została wprowadzona w ES 2015, warto dodać alternatywną implementację na początku kodu programu, jeśli kod uruchamiamy w przeglądarce internetowej.
xxxxxxxxxx
1
if (Math.trunc == null) {
2
Math.trunc = function(value) {
3
return value < 0 ? Math.ceil(value) : Math.floor(value);
4
};
5
}
6
7
8
// Przykład użycia:
9
10
console.log( Math.trunc( 5 )); // 5
11
console.log( Math.trunc( 3.14 )); // 3
12
console.log( Math.trunc( -3.14 )); // -3
13
console.log( Math.trunc( 0.123 )); // 0
14
console.log( Math.trunc( -0.123 )); // -0