Currently I want to find out the number of digits in the integer part of a decimal number.


I am getting correct value as 3.

Just wanted to know if there is any direct function available or better way to do this ?

  • 2
    This approach you are taking will not work for any numbers greater than 1000: format() will add in commas (or other characters, depending on your user's locale). For example, system.debug((12895.95).intValue().format().length()); will return 6. – SFDC Neuf Jan 31 '17 at 17:40

Here you go:

Decimal x = -85695.95;
system.debug(x.precision() + ' - ' + x.scale()); // you want (x.precision() - x.scale())

where Decimal methods:

scale() Returns the scale of the Decimal, that is, the number of decimal places.

precision() Returns the total number of digits for the Decimal.

  • I am getting the result as USER_DEBUG [1]|DEBUG|5 - 2 . Does it actually subtract like that or any function needs to be used? – Vanilla_Sky Feb 1 '17 at 1:52
  • You have to do x.precision() - x.scale() that I have in the comments section. – o-lexi Feb 1 '17 at 4:09

Sure, if you want to stick with numbers, this Execute Anonymous script illustrates a different approach.

static Integer length(Decimal input)
    return (input == 0) ? 1 : 1 + (Integer)Math.floor(Math.log10(Math.abs(input)));
system.assertEquals(3, length(895.95));

Note that you log10(0) is infinity, so you need to handle that edge case. You can also add null handling if you wish. Anyway, log10 basically gives you the number of tens places you have minus one. With negative numbers, you'll get a NaN value, so you have to take the absolute value.

  • Will add more explanation shortly. – Adrian Larson Jan 31 '17 at 17:31
  • Shouldn't the return be (input == 0) ? 1 : 1 + (Integer)Math.floor(Math.log10(Math.abs(input)));? The log function isn't defined for negative numbers. – SFDC Neuf Jan 31 '17 at 17:46
  • Yeah adding that in my edit. – Adrian Larson Jan 31 '17 at 17:47
  • ...and this, ladies, gentlemen, and those identifying as non-binary, is what we call an elegant solution. On that note, if you're just adding one to the floor, why not use Math.ceil() instead? – Derek F Jan 31 '17 at 18:09
  • 1
    It wouldn't give the correct result for values between 0 (exclusive) and 1 (inclusive). – Adrian Larson Jan 31 '17 at 18:19

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.