Java: Count the number of decimal places in a given number
Write a Java program to count the number of decimal places in a given number.
Sample Solution-1:
Java Code:
public class test {
public static void main(String[] args) {
String n = "123";
System.out.println("Original Number: "+n);
System.out.println("Number of decimal places in the said number: "+validate(n));
n = "112.3";
System.out.println("\nOriginal Number: "+n);
System.out.println("Number of decimal places in the said number: "+validate(n));
n = "112.03";
System.out.println("\nOriginal Number: "+n);
System.out.println("Number of decimal places in the said number: "+validate(n));
n = "112.233";
System.out.println("\nOriginal Number: "+n);
System.out.println("Number of decimal places in the said number: "+validate(n));
}
public static Integer validate(String n) {
if(n.contains("."))
return n.replaceAll(".*\\.(?=\\d?)", "").length();
return 0;
}
}
Sample Output:
Original Number: 123 Number of decimal places in the said number: 0 Original Number: 112.3 Number of decimal places in the said number: 1 Original Number: 112.03 Number of decimal places in the said number: 2 Original Number: 112.233 Number of decimal places in the said number: 3
Pictorial Presentation:
Flowchart :
Sample Solution-2:
Java Code:
public class test {
public static void main(String[] args) {
String n = "123";
System.out.println("Original Number: "+n);
System.out.println("Number of decimal places in the said number: "+validate(n));
n = "112.3";
System.out.println("\nOriginal Number: "+n);
System.out.println("Number of decimal places in the said number: "+validate(n));
n = "112.03";
System.out.println("\nOriginal Number: "+n);
System.out.println("Number of decimal places in the said number: "+validate(n));
n = "112.233";
System.out.println("\nOriginal Number: "+n);
System.out.println("Number of decimal places in the said number: "+validate(n));
}
public static Integer validate(String n) {
int ctr = n.indexOf(".");
return ctr > 0 ? n.length() - ctr - 1 : 0;
}
}
Sample Output:
Original Number: 123 Number of decimal places in the said number: 0 Original Number: 112.3 Number of decimal places in the said number: 1 Original Number: 112.03 Number of decimal places in the said number: 2 Original Number: 112.233 Number of decimal places in the said number: 3
Flowchart :
Java Code Editor:
Contribute your code and comments through Disqus.
Previous: Replace all the vowels in a given string with a specified character.
Next: Validate a personal identification number (PIN).What is the difficulty level of this exercise?
Test your Programming skills with w3resource's quiz.
- Weekly Trends and Language Statistics
- Weekly Trends and Language Statistics