Query about output in "Currency converting problem in Java" - java

Everything is Ok, I also get exact output . But when I run it in hackerrank it doesnt show the "sign/symbol" of Chinese & France currency. So it is not accepted.
What should I do now?
import java.io.*;
import java.util.*;
import java.text.*;
import java.math.*;
import java.util.regex.*;
import java.text.NumberFormat;
class Solution {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
double amount = scanner.nextDouble();
Locale indiaLocale = new Locale("en", "IN");
NumberFormat USA = NumberFormat.getCurrencyInstance(Locale.US);
NumberFormat CHINA = NumberFormat.getCurrencyInstance(Locale.CHINA);
NumberFormat INDIA = NumberFormat.getCurrencyInstance(indiaLocale);
NumberFormat FRANCE = NumberFormat.getCurrencyInstance(Locale.FRANCE);
String usa = USA.format(amount);
String india = INDIA.format(amount);
String china = CHINA.format(amount);
String france = FRANCE.format(amount);
System.out.println("USA: " +usa);
System.out.println("India: " +india);
System.out.println("China: " +china);
System.out.println("France: " +france);
}
}

You need to do something like this:
static public void displayCurrency( Locale currentLocale) {
Double currencyAmount = new Double(9876543.21);
Currency currentCurrency = Currency.getInstance(currentLocale);
NumberFormat currencyFormatter =
NumberFormat.getCurrencyInstance(currentLocale);
System.out.println( currentLocale.getDisplayName() + ", " +
currentCurrency.getDisplayName() + ": " +
currencyFormatter.format(currencyAmount));
}
Look here for more details: https://docs.oracle.com/javase/tutorial/i18n/format/numberFormat.html

Currency eur = java.util.Currency.getInstance("EUR");
NumberFormat EUR = NumberFormat.getCurrencyInstance(Locale.FRANCE);
EUR.setCurrency(eur);
System.out.println(EUR.format(34));
This should work, assuming you actually want to use CFP and not EUR. You'll have to look up the currency codes for each currency you want.

Related

RegEx help to replace substring

I have a String:
StartTime-2014-01-14 12:05:00-StartTime
The requirement is to replace the timestamp with current timestamp.
I tried the below code which is not giving me the expected output:
String st = "StartTime-2014-01-14 12:05:00-StartTime";
String replace = "StartTime-2014-01-14 13:05:00-StartTime";
Pattern COMPILED_PATTERN = Pattern.compile(st, Pattern.CASE_INSENSITIVE);
Matcher matcher = COMPILED_PATTERN.matcher(DvbseContent);
String f = matcher.replaceAll(replace);
Expected Output is:
StartTime-<Current_Time_stamp>-StartTime
Or instead of Regex, you can just use indexOf and lastIndexOf:
String f = "StartTime-2014-01-14 12:05:00-StartTime";
String timestamp = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss")
.format(new java.util.Date());
String newString = f.substring(0, f.indexOf("-") + 1)
+ timestamp
+ f.substring(f.lastIndexOf("-"));
Output:
StartTime-2014-02-10 12:52:47-StartTime
You could match it like this:
(StartTime-).*?(-StartTime)
and replace it with this (or similar):
"$1" + current_time_stamp + "$2"
Example Java Code:
import java.util.*;
import java.util.Date;
import java.lang.*;
import java.io.*;
import java.util.regex.*;
class Ideone
{
public static void main (String[] args) throws java.lang.Exception
{
java.util.Date timestamp = new java.util.Date();
String search = "StartTime-2014-01-14 12:05:00-StartTime";
String regex = "(StartTime-).*?(-StartTime)";
String replacement = "$1"+ timestamp + "$2";
String result = search.replaceAll(regex, replacement);
System.out.println(result);
};
};
Output:
StartTime-Fri Feb 14 08:53:57 GMT 2014-StartTime

How do I redirect Console Output to GUI Form?

I'm taking a Java programming class at school and we've been working on a project in class - dealing with console applications. For the coming week, we're moving on to working on creating GUI applications with JAVA and I had an idea of what to do with one of my projects.
I wanted to redirect the console output to a text area inside the GUI. But I don't know if this is possible, or how to do it. Is it possible, if so, can somebody help me. I'm trying to design my form so that it looks like a cash register (with the receipt on one side of the register). In this case, the receipt will be the redirected console output.
Any help would be greatly appreciated.
Here's my source code:
package autoshop_invoice;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.text.NumberFormat;
import java.util.logging.Level;
import java.util.logging.Logger;
public class AutoShop_Invoice
{
public static void total_sales() throws IOException
{
String text = "";
String part_number = "";
int num_items = 0;
double price = 0.0;
double tax = 0.0;
double total_sale = 0.0;
//Prompt user for part number and store value in variable part_number.
System.out.println("Enter Part Number then hit enter.");
BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
try
{
part_number = in.readLine();
} catch (IOException ex)
{
Logger.getLogger(AutoShop_Invoice.class.getName()).log(Level.SEVERE, null, ex);
}
//Prompt user to enter number of items sold and store value in variable num_items.
System.out.println("Enter Number of Items sold then hit enter.");
in = new BufferedReader(new InputStreamReader(System.in));
text = in.readLine();
num_items = Integer.parseInt(text);
//Prompt user to enter Price per Item and store value in variable num_items.
System.out.println("Enter Price per Item then hit enter.");
in = new BufferedReader(new InputStreamReader(System.in));
text = in.readLine();
price = Double.parseDouble(text);
//Display the total sale WITH tax calculated.
total_sale = num_items * price;
tax = total_sale * .06;
total_sale = total_sale + tax;
//DecimalFormat df = new DecimalFormat("#.##");
NumberFormat nf = NumberFormat.getCurrencyInstance(); //Get the current system locale currency
System.out.println();
System.out.println("***********************************");
System.out.print("Part Number: " + part_number + " "); //Display the Part Number being sold
System.out.println("QTY: " + num_items); //Display the quantity of items sold
System.out.println("Sub-Total is: " + nf.format(total_sale)); //Display sub-total rounded to 2 decimal points
System.out.println("MD Sales Tax due (6%): " + nf.format(tax)); //Display the calculated sales tax
//Display grand-total rounded to 2 decimal points and formatted with the locale currency
//System.out.println("Grand-Total sales is: " + df.format(nf.format(total_sale + tax)));
System.out.println("Grand-Total sales is: " + nf.format(total_sale + tax));
System.out.println("***********************************");
}
/**
* #param args the command line arguments
*/
public static void main(String[] args) throws IOException
{
// TODO code application logic here
total_sales();
}
}
Write your own OutputStream implementation that adds any bytes written to the text area. Then wrap it in a PrintStream and pass it to System.setOut():
System.setOut(new PrintStream(myTextAreaOutputStream));
You can use Java Swing to easily create a form and implement its functionality.
Take a look at this tutorial: http://docs.oracle.com/javase/tutorial/uiswing/start/
A walk through on a basic project starts here using Netbeans http://docs.oracle.com/javase/tutorial/uiswing/learn/settingup.html
It's pretty straight forward. Lay out the controls, and then implement the functionality. I think their Celsius converter example will get you very close to finishing your project with just a few modifications.

How to Extract float numeric data from a string

Hey Guys i am using Google Currency Api to request for currency conversions information.
For example i use Google Currency Api
to convert 1USD to my local Currency.
The string returned is {lhs: "1 U.S. dollar",rhs: "2 481.38958 Ugandan shillings",error: "",icc: true}
I need java code to extract the 2481.38958 float data type and save it in a float Variable.
Please Help.
Thanks alot.
For your input JSON string:
{lhs: "1 U.S. dollar",rhs: "2481.38958 Ugandan shillings",error: "",icc: true}
Using http://json-lib.sourceforge.net/ :
JSONObject json = (JSONObject) JSONSerializer.toJSON( jsonTxt );
String dollarString = json.getFloat( "rhs" );
float dollars = Float.parseFloat(dollarString.split(" ")[0]);
Considering the value always will be between rhs: and a word.
String str = "{lhs: \"1 U.S. dollar\",rhs: \"2 481.38958 Ugandan shillings\",error: \"\",icc: true}";
Matcher m = Pattern.compile("rhs:\\s.*?([\\d\\s\\.]+)\\s\\w+").matcher(str);
m.find();
float value = Float.parseFloat(m.group(1).replaceAll("[^\\d\\.]", ""));
System.out.println(value);
This string is at JSON format. There are libs for manipulate this as an object.
Examples : GSON (http://code.google.com/p/google-gson/) or http://www.json.org/java/
Something like :
new JSONObject("{lhs: "1 U.S. dollar",rhs: "2 481.38958 Ugandan shillings",error: "",icc: true}").get("rhs")
And after you have to suppress unit, maybe with a regexp.
And finally... Float.parseFloat("2 481.38958")
If the response always contains the same pattern (with Ugandan shillings text), one possible way of doing it is something like this:
package so;
import java.util.StringTokenizer;
public class DemoString {
public static void main(String[] args) {
String s = new String("{lhs: \"1 U.S. dollar\",rhs: \"2 481.38958 Ugandan shillings\",error: \"\",icc: true}") ;
StringTokenizer st = new StringTokenizer(s, "\"");
st.nextToken(); //{lhs:
st.nextToken(); //1 U.S. dollar
st.nextToken(); //,rhs:
String value = st.nextToken(); //2 481.38958 Ugandan shillings
String num = value.substring(0, value.indexOf("U")); // 2 481.38958
num = num.replaceAll(" ", "");
Float fnum = 0f;
try {
fnum = Float.parseFloat(num);
} catch (Exception e) {
e.printStackTrace(System.out);
}
System.out.println("The float number is: " + fnum.toString());
}
}

Formatting Currencies in Foreign Locales in Java

I'm doing my best to find a way to format foreign currencies across various locales which are not default for that currency, using Java. I've found java.util.Currency, which can represent the proper symbol to use for various locales. That is, for USD, it provides me the symbol $ in the US, and US$ or USD in other nations. Also, I've found java.text.NumberFormat, which will format a currency for a specific locale. My problem - util.Currency will provide proper symbols and codes for representing currencies in their non-default locales, but will not format currency in any locale-specific way. NumberFormat assumes that the number I pass it, with a locale, is the currency of that locale, not a foreign currency.
For example, if I use getCurrencyInstance(Locale.GERMANY) and then format (1000) it assumes I am formatting 1000 euro. In reality, I may need the correct German-localized representation (correct decimal and thousands separator, whether to put the symbol before or after the amount) for USD, or Yen, or any other currency. The best I've been able to derive so far is to format a number using NumberFormat, then search the output for non-digit characters and replace them with symbols derived from util.Currency. However, this is very brittle, and probably not reliable enough for my purposes. Ideas? Any help is much appreciated.
Try using setCurrency on the instance returned by getCurrencyInstance(Locale.GERMANY)
Broken:
java.text.NumberFormat format = java.text.NumberFormat.getCurrencyInstance(java.util.Locale.GERMANY);
System.out.println(format.format(23));
Output: 23,00 €
Fixed:
java.util.Currency usd = java.util.Currency.getInstance("USD");
java.text.NumberFormat format = java.text.NumberFormat.getCurrencyInstance(java.util.Locale.GERMANY);
format.setCurrency(usd);
System.out.println(format.format(23));
Output: 23,00 USD
I would add to answer from les2 https://stackoverflow.com/a/7828512/1536382 that I believe the number of fraction digits is not taken from the currency, it must be set manually, otherwise if client (NumberFormat) has JAPAN locale and Currency is EURO or en_US, then the amount is displayed 'a la' Yen', without fraction digits, but this is not as expected since in euro decimals are relevant, also for Japanese ;-).
So les2 example could be improved adding format.setMaximumFractionDigits(usd.getDefaultFractionDigits());, that in that particular case of the example is not relevant but it becomes relevant using a number with decimals and Locale.JAPAN as locale for NumberFormat.
java.util.Currency usd = java.util.Currency.getInstance("USD");
java.text.NumberFormat format = java.text.NumberFormat.getCurrencyInstance(
java.util.Locale.JAPAN);
format.setCurrency(usd);
System.out.println(format.format(23.23));
format.setMaximumFractionDigits(usd.getDefaultFractionDigits());
System.out.println(format.format(23.23));
will output:
USD23
USD23.23
In NumberFormat code something similar is done for the initial/default currency of the format, calling method DecimalFormat#adjustForCurrencyDefaultFractionDigits. This operation is not done when the currency is changed afterwards with NumberFormat.setCurrency
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();
NumberFormat lp; //Local Payment
lp = NumberFormat.getCurrencyInstance(Locale.US);
System.out.println("US: " + lp.format(payment));
lp = NumberFormat.getCurrencyInstance(new Locale("en", "in"));
System.out.println("India: " + lp.format(payment));
lp = NumberFormat.getCurrencyInstance(Locale.CHINA);
System.out.println("China: " + lp.format(payment));
lp = NumberFormat.getCurrencyInstance(Locale.FRANCE);
System.out.println("France: " + lp.format(payment));
}
}
Scanner scanner = new Scanner(System.in);
double payment = scanner.nextDouble();
scanner.close();
java.text.NumberFormat formatUS = java.text.NumberFormat.getCurrencyInstance(java.util.Locale.US);
String us=formatUS.format(payment);
java.text.NumberFormat formatIn = java.text.NumberFormat.getCurrencyInstance(new java.util.Locale("en","in"));
String india=formatIn.format(payment);
java.text.NumberFormat formatChina = java.text.NumberFormat.getCurrencyInstance(java.util.Locale.CHINA);
String china=formatChina.format(payment);
java.text.NumberFormat formatFrance = java.text.NumberFormat.getCurrencyInstance(java.util.Locale.FRANCE);
String france=formatFrance.format(payment);
System.out.println("US: " + us);
System.out.println("India: " + india);
System.out.println("China: " + china);
System.out.println("France: " + france);
Code below, Ref Java Locale:
Scanner scanner = new Scanner(System.in);
double payment = scanner.nextDouble();
scanner.close();
// Write your code here.
String china = NumberFormat.getCurrencyInstance(new Locale("zh", "CN")).format(payment);
String india = NumberFormat.getCurrencyInstance(new Locale("en", "IN")).format(payment);
String us = NumberFormat.getCurrencyInstance(Locale.US).format(payment);
String france = NumberFormat.getCurrencyInstance(Locale.FRANCE).format(payment);
System.out.println("US: " + us);
System.out.println("India: " + india);
System.out.println("China: " + china);
System.out.println("France: " + france);
Better way is just to import java.util.Locale.
Then use the method like this:
NumberFormat.getCurrencyInstance(Locale.theCountryYouWant);
e.g. NumberFormat.getCurrencyInstance(Locale.US);
import java.util.*;
import java.text.*;
public class CurrencyConvertor {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
double curr= scanner.nextDouble();
scanner.close();
if(curr>=0 && curr<=1000000000){
NumberFormat france = NumberFormat.getCurrencyInstance(Locale.FRANCE);
NumberFormat us = NumberFormat.getCurrencyInstance(Locale.US);
NumberFormat china = NumberFormat.getCurrencyInstance(Locale.CHINA);
NumberFormat india = NumberFormat.getCurrencyInstance(Locale.ENGLISH);
System.out.println("India: "+NumberFormat.getCurrencyInstance(new Locale("en","IN")).format(curr));
System.out.println("US: " + us.format(curr));
System.out.println("China: "+ china.format(curr));
System.out.println("France: " + france.format(curr));
}
}
}
Try this, Using Locale, you can pass the country and get the currency.
Locale currentLocale = Locale.GERMANY;
Double currencyAmount = new Double(9876543.21);
Currency currentCurrency = Currency.getInstance(currentLocale);
NumberFormat currencyFormatter =
NumberFormat.getCurrencyInstance(currentLocale);
System.out.println(
currentLocale.getDisplayName() + ", " +
currentCurrency.getDisplayName() + ": " +
currencyFormatter.format(currencyAmount));
Output:
German (Germany), Euro: 9.876.543,21 €

need space between currency symbol and amount

I'm trying to print INR format currency like this:
NumberFormat fmt = NumberFormat.getCurrencyInstance();
fmt.setCurrency(Currency.getInstance("INR"));
fmt.format(30382.50);
shows Rs30,382.50, but in India its written as Rs. 30,382.50(see http://www.flipkart.com/)
how to solve without hardcoding for INR?
It's a bit of a hack but in a very similar situation, I used something like this
NumberFormat format = NumberFormat.getCurrencyInstance(new Locale("en", "in"));
String currencySymbol = format.format(0.00).replace("0.00", "");
System.out.println(format.format(30382.50).replace(currencySymbol, currencySymbol + " "));
all the currencies I had to deal with involved two decimal places so i was able to do "0.00" for all of them but if you plan to use something like Japanese Yen, this has to be tweaked. There is a NumberFormat.getCurrency().getSymbol(); but it returns INR instead for Rs. so that cannot be used for getting the currency symbol.
An easier method, kind of workaround.
For my locale, the currency symbol is "R$"
public static String moneyFormatter(double d){
DecimalFormat fmt = (DecimalFormat) NumberFormat.getInstance();
Locale locale = Locale.getDefault();
String symbol = Currency.getInstance(locale).getSymbol(locale);
fmt.setGroupingUsed(true);
fmt.setPositivePrefix(symbol + " ");
fmt.setNegativePrefix("-" + symbol + " ");
fmt.setMinimumFractionDigits(2);
fmt.setMaximumFractionDigits(2);
return fmt.format(d);
}
Input:
moneyFormatter(225.0);
Output:
"R$ 225,00"
See if this works:
DecimalFormat fmt = (DecimalFormat) NumberFormat.getInstance();
fmt.setGroupingUsed(true);
fmt.setPositivePrefix("Rs. ");
fmt.setNegativePrefix("Rs. -");
fmt.setMinimumFractionDigits(2);
fmt.setMaximumFractionDigits(2);
fmt.format(30382.50);
Edit: Fixed the first line.
I dont think you can.
You should take a look at http://site.icu-project.org/
There might be better locale-specific currency formatting provided by icu4j.
I don't see any easy way to do this. Here's what I came up with...
The key to getting the actual currency symbol seems to be passing the destination locale into Currency.getSymbol:
currencyFormat.getCurrency().getSymbol(locale)
Here's some code that seems like it mostly works:
public static String formatPrice(String price, Locale locale, String currencyCode) {
NumberFormat currencyFormat = NumberFormat.getCurrencyInstance(locale);
Currency currency = Currency.getInstance(currencyCode);
currencyFormat.setCurrency(currency);
try {
String formatted = currencyFormat.format(NumberFormat.getNumberInstance().parse(price));
String symbol = currencyFormat.getCurrency().getSymbol(locale);
// Different locales put the symbol on opposite sides of the amount
// http://en.wikipedia.org/wiki/Currency_sign
// If there is already a space (like the fr_FR locale formats things),
// then return this as is, otherwise insert a space on either side
// and trim the result
if (StringUtils.contains(formatted, " " + symbol) || StringUtils.contains(formatted, symbol + " ")) {
return formatted;
} else {
return StringUtils.replaceOnce(formatted, symbol, " " + symbol + " ").trim();
}
} catch (ParseException e) {
// ignore
}
return null;
}
Sorry for Kotlin I came here from android).
As I understood there is no correct solutions for that, so that's why my solution is also hack)
fun formatBalance(
amount: Float,
currencyCode: String,
languageLocale: Locale
): String {
amount can be String as well.
val currencyFormatter: NumberFormat = NumberFormat.getCurrencyInstance(languageLocale)
currencyFormatter.currency = Currency.getInstance(currencyCode)
val formatted = currencyFormatter.format(amount)
formatted will get amount with currency from correct side but without space. (Example: 100$, €100)
val amountFirstSymbol = amount.toString()[0]
val formattedFirstSymbol = formatted[0]
val currencySymbolIsBefore = amountFirstSymbol != formattedFirstSymbol
Then I use this little hack to understand if currency symbol is before amount. So for example amount is 100 then amountFirstSymbol will be "1". And if formatted is 100$ then formattedFirstSymbol also will be "1". That means we can put our currency symbol behind amount but now with space.
val symbol = currencyFormatter.currency?.symbol
return if (currencySymbolIsBefore) "$symbol $amount"
else "$amount $symbol"
Here what I do to add space after currency symbol:
DecimalFormat numberFormat = (DecimalFormat) NumberFormat.getCurrencyInstance(new Locale("id", "ID"));
DecimalFormatSymbols symbol = new DecimalFormatSymbols(new Locale("id", "ID"));
// Add space to currency symbol
symbol.setCurrencySymbol(symbol.getCurrencySymbol() + " ");
numberFormat.setDecimalFormatSymbols(symbol);

Categories