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.
system.debug((12895.95).intValue().format().length());
will return6
.