Java Currency Formatter Solution
Problem Overview
Original Problem: Java Currency Formatter | HackerRank
Difficulty: Easy
Category: Formatting, Internationalization
Description: Given a decimal number representing an amount of money, format and display it according to the currency formatting standards used in the United States, India, China, and France.
Understanding the Problem
This problem focuses on the concept of internationalization, which involves designing software so it can easily be adapted to different languages and regions without changing the underlying code.
Input:
A single double value representing the payment amount.
Output:
Four lines, each showing the currency formatted for a different locale
Initial Reasoning
Since currency formatting depends on the regional conventions of different countries, Java provides the NumberFormat.getCurrencyInstance(Locale) method to handle these variations. Java has built-in Locale constants for the US, China, and France. However, it does not provide a built-in locale for India, so we must create a custom Locale object.
Pseudocode
// Main method:
Read the input payment as a double
Create a locale object for India
Create currency formatters for each locale (US, India, China, France)
Format the payment using each formatter
Print the results
Solution Code
// Note this is one of many possible solutions
import java.text.NumberFormat;
import java.util.Locale;
import java.util.Scanner;
public class Solution {
public static void main(String[] args) {
// Reading the payment amount
Scanner scanner = new Scanner(System.in);
double payment = scanner.nextDouble();
scanner.close();
// Creating a custom Locale for India as Java does not have a built-in locale
Locale indiaLocale = new Locale("en", "IN");
// Getting currency formatters for each locale
NumberFormat usFormatter = NumberFormat.getCurrencyInstance(Locale.US);
NumberFormat indiaFormatter = NumberFormat.getCurrencyInstance(indiaLocale);
NumberFormat chinaFormatter = NumberFormat.getCurrencyInstance(Locale.CHINA);
NumberFormat franceFormatter = NumberFormat.getCurrencyInstance(Locale.FRANCE);
// Formatting the payment amount using each formatter
String us = usFormatter.format(payment);
String india = indiaFormatter.format(payment);
String china = chinaFormatter.format(payment);
String france = franceFormatter.format(payment);
// Printing the formatted results
System.out.println("US: " + us);
System.out.println("India: " + india);
System.out.println("China: " + china);
System.out.println("France: " + france);
}
}