Java Currency Formatter

  • + 0 comments

    //Indian rupee Rs.1... was causing problem because my code was writing in hindi characters // at first. And second, third, etc. times as well //The next problem, when I thought I found the solution: //Error: I used a non-ASCII character ("₹") - Headshot, thanks Java8 //Finally there is a working solution (I got help from a smarter one, thx for him). I didn't know it "currInr.startsWith" //I hope I could help if someone would have need it

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

    public class Solution {

    public static void main(String[] args) {
        /* Enter your code here. Read input from STDIN. Print output to STDOUT. Your class should be named Solution. */
    
        Scanner scanner = new Scanner(System.in);
        String amount = scanner.nextLine();
        scanner.close();
    
        Currency usd = Currency.getInstance("USD");
        Currency cny = Currency.getInstance("CNY");
        Currency eur = Currency.getInstance("EUR");
    
        Locale INDIA = new Locale("en", "IN");
        Currency inr = Currency.getInstance("INR");
    
        NumberFormat inrFormatter = NumberFormat.getCurrencyInstance(INDIA);
        inrFormatter.setCurrency(inr);
        inrFormatter.setMaximumFractionDigits(2);
        inrFormatter.setMinimumFractionDigits(2);
    
        NumberFormat usdFormatter = NumberFormat.getCurrencyInstance(Locale.US);
        usdFormatter.setCurrency(usd);
    
        NumberFormat eurFormatter = NumberFormat.getCurrencyInstance(Locale.FRANCE);
        eurFormatter.setCurrency(eur);
    
        NumberFormat cnyFormatter = NumberFormat.getCurrencyInstance(Locale.CHINA);
        cnyFormatter.setCurrency(cny);
    
        BigDecimal amt = new BigDecimal(amount);
        String currInr = inrFormatter.format(amt);
        if (!currInr.startsWith("Rs.")) {
            currInr = "Rs." + currInr.substring(1);
        }
        String currUs = usdFormatter.format(amt);
        String currFr = eurFormatter.format(amt);
        String currCn = cnyFormatter.format(amt);
    
        System.out.println("US: " + currUs);
        System.out.println("India: " + currInr);
        System.out.println("China: " + currCn);
        System.out.println("France: " + currFr);
    
    }
    

    }