Monday, 27 June 2016

Program to perform Sum of Digits On Double Datatype.

Explanation :
If n=123.56 then Output will be 6:11 .
If n=401 then Output will be 5:0 .

Code:

import java.util.Scanner;
public class DoubleSumOfDigits
{
    String getSum(double d)
    {
        String s=Double.toString(d);
        int res1=0,res2=0;
        int i=s.indexOf(".");
       
        for(int j=0;j<i;j++)
        {
            int n=s.charAt(j);
            res1+=Character.getNumericValue(n);
        }
        for(int j=i+1;j<s.length();j++)
        {
            res2+=Character.getNumericValue(s.charAt(j));
        }
        String fnl=Integer.toString(res1)+":"+Integer.toString(res2);
        return fnl;
    }
   
    public static void main(String[] args)
    {
       
        Scanner sc=new Scanner(System.in);
        System.out.println("Enter any double number");
       
        DoubleSumOfDigits das=new DoubleSumOfDigits();
        String b=das.getSum(sc.nextDouble());
        System.out.println(b);

        sc.close();
    }
}

No comments:

Post a Comment