Header Ad

HackerRank Java Currency Formatter problem solution

In this HackerRank Java Currency Formatter problem in the java programming language you have Given a double-precision number, payment, denoting an amount of money, use the NumberFormat class' getCurrencyInstance method to convert the payment into the US, Indian, Chinese, and French currency formats. Then print the formatted values.

HackerRank Java Currency Formatter problem solution


HackerRank Java Currency Formatter problem solution.

import java.util.*;
import java.text.*;

public class Solution {
    
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        double payment = scanner.nextDouble();
        scanner.close();
        
        // Write your code here.
        /* Create custom Locale for India. 
          I used the "IANA Language Subtag Registry" to find India's country code */
        Locale indiaLocale = new Locale("en", "IN");

        /* Create NumberFormats using Locales */
        NumberFormat us     = NumberFormat.getCurrencyInstance(Locale.US);
        NumberFormat india  = NumberFormat.getCurrencyInstance(indiaLocale);
        NumberFormat china  = NumberFormat.getCurrencyInstance(Locale.CHINA);
        NumberFormat france = NumberFormat.getCurrencyInstance(Locale.FRANCE);

        /* Print output */        
        System.out.println("US: "     + us.format(payment));
        System.out.println("India: "  + india.format(payment));
        System.out.println("China: "  + china.format(payment));
        System.out.println("France: " + france.format(payment));
    
    }
}



Second solution in java8 programming.

import java.io.*;
import java.util.*;
import java.text.*;
import java.math.*;
import java.util.regex.*;

public class Solution {
    
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        double payment = scanner.nextDouble();
        scanner.close();
        NumberFormat usNumbers = NumberFormat.getCurrencyInstance(Locale.US);
        NumberFormat indiaNumbers = NumberFormat.getCurrencyInstance(new Locale("en", "IN"));
        System.out.printf("US format = %s%n", usNumbers.format(payment));
        System.out.printf("India format = %s%n", indiaNumbers.format(payment));
    }
}

Post a Comment

5 Comments

  1. This maybe because en,IN does not return Rs now it returns the ruppee symbol

    ReplyDelete