DE
JavaScript - Math.floor() Methode - Beispiel
3 points
Die Math.floor()
Funktion gibt einen ganzzahligen Wert zurück, der kleiner oder gleich dem Argument ist - Ergebnis einer Abrundungsoperation.
xxxxxxxxxx
1
console.log( Math.floor( 5 ) ); // 5
2
3
console.log( Math.floor( 2.49 ) ); // 2
4
console.log( Math.floor( 2.50 ) ); // 2
5
console.log( Math.floor( 2.51 ) ); // 2
6
7
console.log( Math.floor( -2.49 ) ); // -3
8
console.log( Math.floor( -2.50 ) ); // -3
9
console.log( Math.floor( -2.51 ) ); // -3
10
11
console.log( Math.floor( 0.999 ) ); // 0
12
console.log( Math.floor( 1.001 ) ); // 1
13
console.log( Math.floor( -1.001 ) ); // -2
Syntax | Math.floor(Zahl) |
Parameter | number - Wert für Ganzzahl oder Gleitkommazahl (primitiver Wert). |
Ergebnis |
Abgerundeter Wenn der Wenn der Wenn der |
Beschreibung | floor ist eine statische Methode, die nur einen Parameter verwendet und einen abgerundeten Wert zurückgibt. |
xxxxxxxxxx
1
function floorPrecised(number, precision) {
2
var power = Math.pow(10, precision);
3
4
return Math.floor(number * power) / power;
5
}
6
7
// Beispiel:
8
9
console.log( floorPrecised( 5 , 0 ) ); // 5
10
console.log( floorPrecised( 5. , 0 ) ); // 5
11
console.log( floorPrecised( .5, 0 ) ); // 0
12
13
console.log( floorPrecised( 1.1234, 0 ) ); // 1
14
console.log( floorPrecised( 1.1234, 1 ) ); // 1.1
15
console.log( floorPrecised( 1.1235, 2 ) ); // 1.12
16
console.log( floorPrecised( 1.1235, 3 ) ); // 1.123
17
18
console.log( floorPrecised( -1.1234, 0 ) ); // -2
19
console.log( floorPrecised( -1.1234, 1 ) ); // -1.2
20
console.log( floorPrecised( -1.1234, 2 ) ); // -1.13
21
console.log( floorPrecised( -1.1234, 3 ) ); // -1.124
22
23
console.log( floorPrecised( 1234, -1 ) ); // 1230
24
console.log( floorPrecised( 1234, -2 ) ); // 1200
25
console.log( floorPrecised( 1234, -3 ) ); // 1000
26
27
console.log( floorPrecised( 5_000.000_001, 0 ) ); // 5000
28
console.log( floorPrecised( 5_000.000_001, 6 ) ); // 5000.000001
29
console.log( floorPrecised( 5_000.000_001, -3 ) ); // 5000