3

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

system.debug((895.95).intValue().format().length());

I am getting correct value as 3.

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

1
  • 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
    Commented Jan 31, 2017 at 17:40

2 Answers 2

10

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.

2
  • 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? Commented Feb 1, 2017 at 1:52
  • You have to do x.precision() - x.scale() that I have in the comments section.
    – o-lexi
    Commented Feb 1, 2017 at 4:09
4

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.

5
  • Will add more explanation shortly.
    – Adrian Larson
    Commented Jan 31, 2017 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
    Commented Jan 31, 2017 at 17:46
  • Yeah adding that in my edit.
    – Adrian Larson
    Commented Jan 31, 2017 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
    Commented Jan 31, 2017 at 18:09
  • 1
    It wouldn't give the correct result for values between 0 (exclusive) and 1 (inclusive).
    – Adrian Larson
    Commented Jan 31, 2017 at 18:19

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .