function readOnly(count){ }
Starting November 20, the site will be set to read-only. On December 4, 2023,
forum discussions will move to the Trailblazer Community.
+ Start a Discussion
Vijay NagarathinamVijay Nagarathinam 

Format SSN number with dashes

Hi All,

I want to format the SSN number with dashes. By default, it will without dashes.

Example : SSN = 1234567891

I want to convert into this format using apex 123-45-7891

Please let me know how to achieve this.

Thanks,
Vijay

 
Eric PepinEric Pepin
string ssn = '123456789';
string formattedSsn = ssn.substring(0, 3) + '-' + ssn.substring(3, 5) + '-' + ssn.substring(5, 9);
system.assertEquals('123-45-6789', formattedSsn);

 
Purushotham YellankiPurushotham Yellanki
Hi,

I like the above answer from Eric, here is one more way to do this

String ssn = '222552222';
String s1;
String s2;
String s3;
if (ssn != null) {
    s1 = ssn.left(3);
    s2 = ssn.right(6);
    s3 = s2.left(2);
    ssn = s1 + '-' + s3 + '-' + s2.right(4);
    System.debug('************' + ssn);
 }
Eric PepinEric Pepin
Hello Vijay, if my answer helped you, would you kindly mark it as Best Answer? Thanks!