0

I have two string values using numbers. How to add(not concatenate) the two string values. Could you please help me.

my code:

string num='2016';
system.debug('first:'+num);
Output: 2016

string num1='2016'+'1';
system.debug('second:'+num1);
Output: 20161

But I need 2017.Is it possible or not this way?

1 Answer 1

4
Integer num = Integer.valueOf('2006');
Integer num2 = Integer.valueOf('1');

Integer result = num + num2;
System.debug(result);

Update as per comment, to transform it to a String:

String str = String.valueOf(result);
System.debug(str);
8
  • i would however put that in a try/Catch block when you do that as you may throw a conversion error if the values are not formatted properly as numbers that you are trying to parse.
    – Ronnie
    Jan 18, 2018 at 5:47
  • for brevity I have omitted try/catch Jan 18, 2018 at 5:48
  • I understand - just thought i would comment it for other users to benefit as well.
    – Ronnie
    Jan 18, 2018 at 5:51
  • @Santanu Boral, Thankyou for quick reply. The above scenario is working fine. But in the this way I am using string. The same output get using string or not? If possible could you please explain me
    – Preeth
    Jan 18, 2018 at 5:54
  • you can get it to a string using String str = String.valueOf(result); System.debug(str); Jan 18, 2018 at 5:58

You must log in to answer this question.

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