How to Trim an Int in Java


Java provides a method in its Math library for rounding values to the nearest whole integer, but no method for rounding a value to some other place, such as the nearest hundreds or thousands place. You will need to implement this yourself, but fortunately it is not a difficult task to pull off.

  • Open "Netbeans" and select "File" and "New class."

  • Type "psvm" to create a main method and paste the following code into it:

    // Trim integer

    int i = 432432;

    i = trimInt(i, 100);


    This defines a large integer and calls a method named "trimInt" on it to round it to the nearest 100. Unfortunately, this method doesn't actually exist yet. You will create it in the next step.

  • Type the following outside the main method:

    static int trimInt(int i, int place) {

    i /= place;

    i *= place;

    return i;


    The method is simple: first the integer is divided by the place amount. Since the result is an integer, everything that is now a decimal value is dropped off. Then, it multiplies by the place value to get back in the appropriate magnitude.

  • Click "Run." The result will be "432400."

Related Searches


Promoted By Zergnet


You May Also Like

Related Searches

Check It Out

Geek Vs Geek: Robot battles, hoverboard drag race, and more

Is DIY in your DNA? Become part of our maker community.
Submit Your Work!