0

I'm looking to validate percentage field type to ensure they contain only one decimal and can be between 0.0 and 100.0.I want to see an error message when more than one decimal is entered.

I tried this: NOT(REGEX(TEXT(ACC__c),"[0-9]{3}+(.[0-9]{1}?)?$"))

But not worked. Any tips would be appreciated.

Thanks

2 Answers 2

0

While creating the % field you can specify the number of decimal places. This is standard functionality. Decimal

Then you can have a simple validation

ACC__C < 0 || ACC__C > 1

To limit values between 0 to 100. Or you can have just this validation. That should also work. On UI, the number would be rounded off.

As noted by sfdcfox below, please check the rounding off for record created via API.

2
  • That's not entirely accurate. If you use an API call/Apex/etc, it's possible to insert values that won't be properly rounded as you expect. I've run into this problem before, it can be hard to track down.
    – sfdcfox
    Commented Apr 22, 2022 at 18:54
  • Thanks @sfdcfox. I added the clarification in the answer.
    – manjit5190
    Commented Apr 22, 2022 at 18:56
1

As a validation rule, you'd multiply by 1000 and round, then multiply by 10, and compare it to multiplying by 10000. If the results don't match, you have more than one decimal present.

ACC__c < 0 || ACC__c > 1 || (FLOOR(ACC__c * 1000) * 10 <> ACC__c * 10000)

This works by checking if the rounded version equals the unrounded version. If they don't match, we'll throw an error.

Note that Percent fields are stored in decimal notation, where 0 means 0% and 1 means 100%. For this reason, we compare the boundaries with 0 and 1.

Alternatively, as @Derek F pointed out, we can save a bunch of compiled size by using MOD:

Acc__c < 0 || Acc__c > 1 || MOD(Acc__c * 10000, 10) <> 0
2
  • MOD(ACC__c * 10000, 10) <> 0 seems to have the same behavior, but is friendlier on the character and compiled sizes in my testing (333 using MOD() vs 1,349 for the FLOOR() approach. The field I used in my test was itself a formula field with a compiled size of 302).
    – Derek F
    Commented Apr 22, 2022 at 19:30
  • @DerekF Thanks for pointing that out. I should have thought of that. I'll add that in.
    – sfdcfox
    Commented Apr 22, 2022 at 20:05

You must log in to answer this question.