(Dart) Round integer to 10,100, 1000 etc.

By | February 27, 2021

If you need to shave off the last few digits of a big int, you can use this simple solution. Came in handy for me when working with milliseconds in timers. Basically you cast the integer to a double and divide it by the number of 0’s you want at the end. Then round, ceil or floor it and turn it back into an int.

For type safety you might have to do some more meticulous work, depending on the language you’re working in. Here’s an example in Dart.

  var integerToRound = 31555;
  var roundedInteger = (integerToRound / 10).floor() * 10;

  //output: 31560

Change the divider and multiplier to the number of zeros you need.

  var integerToRound = 31555;
  var roundedInteger = (integerToRound / 100).floor() * 100;

  //output: 31600

Leave a Reply

Your email address will not be published. Required fields are marked *