Salut !
J'aimerais vous proposer une petite bricole que je viens de produire. Mon besoin étant d'arrondir des nombres après quelques décimales, non pas à l'entier près tel que le propose la fonction native Math.round.
Ça s'utilise très simplement, par exemple :
Code : Sélectionner tout - Visualiser dans une fenêtre à part
1
2
3
4
5 var number = 3.14159265; Math.round(number); // appel naturel, arrondissement à l'entier près : 3 Math.round(number, 1); // arrondissement après une décimale : 3,1 Math.round(number, 3); // arrondissement après trois décimales : 3,142 Math.round(number, 6); // arrondissement après six décimales : 3.141593Note : Ah oui, j'ai failli oublier... J'utilise prototype.js et la méthode Function#wrap. L'adaptation pour s'en dispenser n'est pas très compliquée, le tout étant de conserver une référence à la fonction naturelle Math.round afin de pouvoir l'appeler quand on n'a pas besoin de précision décimale.
Code : Sélectionner tout - Visualiser dans une fenêtre à part
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16 // Math.round redefinition providing the ability to round numbers by considering a certain amount of decimals. Math.round = Math.round.wrap(function(legacy, number, precision) { var result = Number.NaN; // Is a precision given? if(precision != undefined) { // Round the number by considering as many decimals as it is given. result = Math.round(number * Math.pow(10, precision)) / Math.pow(10, precision); } else { // Otherwise, when the call signature is natural (only one parameter), use the legacy function. result = legacy.apply(null, [number]); } return result; });
Partager