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
A MeA Me 

Problem Converting String to Long data type

Hi,

I want to do a Math.mod operation on a string (contains numeric values only) in an apex class. The maximul length of the string is 19.
Here is a sample value : 57901220028758151855

The problem is when I try to convert this to Long using Long.valueOf(string) , there is a type exception : invalid long
So I tried to get the long value using : Decimal.valueOf(string).longValue() , but when I check the value using System.debug  & it is = 2560987807629497007 , not the same as the original, so the mod result is also not correct.
I have to convert to Int, or Long because those are the only 2 types accepted by Math.mod(). and the max length of Integer is too small for these numeric strings.

The same operation is being performed in a validation rule using MOD (VALUE(string),divisor) with no problems.

Please help.

Regards,

A Me

pranav anandpranav anand
please go this link http://salesforcesource.blogspot.in/2008/11/utility-apex-class-to-convert-all-types.html
A MeA Me
Thanks but I dont see how this is related to my problem.
I want to convert String to Long and keep the numbers as is and not the other way round.

Br,
A Me
SarfarajSarfaraj
Range of Long is -2^63 to 2^63 - 1. 57901220028758151855 is more than 2^63 - 1. That is why you are getting the exception while using Long.valueOf.
Decimal however truncates the number to fit in 64 bit. That is why you are getting wrong result. Refer to the following link for more information about primitive data types,
https://www.salesforce.com/us/developer/docs/apexcode/Content/langCon_apex_primitives.htm 
Akhilesh PkAkhilesh Pk

Hi, 
I was stuck with the same issue, I tried everything and realized that its nothing to do with the Long Class, It is the String value that has been passed, Long.valueOf(Str) doesn't take blank spaces, Try to apply Trim() Method before passing the value. That should resolve the issue.

Thanks