Arrondissez à la centaine la plus proche
1. Vue d'ensemble
Dans ce rapide didacticiel, nous allons illustrer commentround up a given number to the nearest hundred.
Par exemple:99 devient100200.2 devient300400 devient400
2. la mise en oeuvre
Tout d'abord, nous allons appelerMath.ceil() sur le paramètre d'entrée. Math.ceil() returns the smallest integer that is greater than or equal to the argument. Par exemple, si l'entrée est de 200,2Math.ceil() renvoie 201.
Ensuite, nous ajoutons 99 au résultat et en divisant par 100. Nous profitons de Integerdivisionto truncate the decimal portion of the quotient. Enfin, nous multiplions le quotient par 100 pour obtenir la sortie souhaitée.
Voici notre implémentation:
static long round(double input) {
long i = (long) Math.ceil(input);
return ((i + 99) / 100) * 100;
};
3. Essai
Testons la mise en œuvre:
@Test
public void givenInput_whenRound_thenRoundUpToTheNearestHundred() {
assertEquals("Rounded up to hundred", 100, RoundUpToHundred.round(99));
assertEquals("Rounded up to three hundred ", 300, RoundUpToHundred.round(200.2));
assertEquals("Returns same rounded value", 400, RoundUpToHundred.round(400));
}
4. Conclusion
Dans cet article rapide, nous avons montré comment arrondir un nombre à la centaine près.
Comme d'habitude, le code complet est disponibleon the GitHub.