I am trying to format double values to currency and then remove the euro sign but my application crashed. can someone tell me where am wrong please?
public class Formatting {
public static String replaceString(String text){
NumberFormat formatter = NumberFormat.getCurrencyInstance();
String moneyString = formatter.format(text);
System.out.println("epargne: "+moneyString);
return text.replaceAll("£", "");
}
public static String convert(double x){
return replaceString(Double.toString(x));
}
}
i called it as follows in class y
double x = a + b + c;
System.out.println(Formatting.convert(x));
format accepts a double, no need to convert that value to a String. replaceAll requires a regexp, you can just simply use replace which requires a single char.
public static String replaceString(double value){
NumberFormat formatter = NumberFormat.getCurrencyInstance();
String currencySymbol = formatter.getCurrency().getSymbol();
String moneyString = formatter.format(value);
return moneyString.replace(currencySymbol, "");
}
public static String convert(double x){
return replaceString(x);
}
As you don't want to get currency returned, you could simply use DecimalFormat which will also give you rounding to 2 decimal places (from your comment):
public static String replaceString(double number) {
NumberFormat formatter = new DecimalFormat("0.00");
return formatter.format(number);
}
Related
Below is the double return type function and i would like to get the answer with precision of 2 zeros. My current answer is coming out to be -4.5. Whereas i want it to be -4.50. Any kind of help will be really appreciated
public double getAmount(){
double ftotal = car.hello();
return Math.round(ftotal * 100)/100.0d;
}
The returned value is a Double so you can't pad 0s to a Double.
So you must format the returned value to create a string, like:
NumberFormat formatter = new DecimalFormat("#0.00");
String number = formatter.format(getTotal());
System.out.println(number);
Refer below code -
import java.text.DecimalFormat;
public class Decimal2{
private static DecimalFormat df2 = new DecimalFormat(".##");
public static void main(String[] args) {
double input = 62.123454;
System.out.println("double : " + df2.format(input));
}
}
Help me please for the next problem:
There is String pattern, assume it's public final static variable. There is string where we search. There is class, simple wrapper to double
public class Wrapper {
private double value;
public double getValue() {
return value;
}
public Wrapper(double value) {
this.value = value;
}
}
I need method
public Wrapper parse(String s, int index)
which returns Wrapper's object if string at the index is double number with maximum 2 digits after decimal point(if there is decimal point at all) and right after number ends there is String pattern after it
For example for strings
String pattern = "money";
String search = "Giveme10.25moneyplease";
parse(search, 6) returns new Wrapper(10.25)
In other cases (index less then zero, greater then length of the string, substring that starts from index isn't number at all or it's double number but it contains more then 2 digits after decimal point or there is no string pattern after number) method must return null
And another method that differs only string pattern must be first and then double number with maximum 2 digits after decimal point and all other the same
String pattern = "money"
String s = "Ihavemoney10.50"
parse1(s, 5) returns new Wrapper(10.50)
You can use DecimalFormat along with ParsePosition like this
import java.text.DecimalFormat;
import java.text.ParsePosition;
public class TestP {
public static void main(String[] args) {
DecimalFormat decimalFormat = new DecimalFormat("00.##'money'");
String search = "Giveme10.25moneyplease";
int index = 6;
//output 10.25
Number number = decimalFormat.parse(search, new ParsePosition(index));
if (number != null) {
String s = number.toString();
if (s.contains(".") && s.length() > 5) {
number = null;
}
}
System.out.println(number);
}
}
The console is telling me it can't find the symbol "getCurrencyInstance()" when I know I properly imported java.text.NumberFormat
I removed some code so it wasn't quite as cluttered; this isn't my whole class.
import java.util.Scanner;
import java.text.NumberFormat;
public class Kohls
{
// initialization
static Prompter prompter;
static Calculator calc;
static Operator operator;
private enum cardColor
{
RED, BLUE, GREEN;
} // end of enum Color
private static class Calculator
{
public int getDiscount(int age, cardColor color)
{
if (age > 62)
// senior discount
return 20;
if (color == cardColor.RED)
{
return 30;
}
else if (color == cardColor.BLUE)
{
return 25;
}
else if (color == cardColor.GREEN)
{
return 15;
}
return 0;
}
public double getSalePrice(int discountPercentage, double price)
{
double salePrice = price - (price * (discountPercentage / 100));
return salePrice;
}
} // end of class Calculator
private class Operator
{
public void getPriceWithDiscount()
{
// prompts
double price = prompter.getPrice();
int age = prompter.getAge();
cardColor color = prompter.getColor();
// discount(s)
int discountPercentage = calc.getDiscount(age, color);
double salePrice = calc.getSalePrice(discountPercentage, price);
NumberFormat fmt = new NumberFormat.getCurrencyInstance();
String salePriceFormat = fmt.format(salePrice);
operator.display(discountPercentage, salePriceFormat);
}
public void display(int discountPercentage, String salePrice)
{
System.out.print("You saved " + discountPercentage + "% on your purchase.");
System.out.print("\nThe price of your purchase with discount is " + salePrice + ".");
}
} // end of class Operator
public Kohls()
{
prompter = new Prompter();
calc = new Calculator();
operator = new Operator();
} // end of constructor
public static void main(String[] args)
{
Kohls kohls = new Kohls();
kohls.operator.getPriceWithDiscount();
} // end of method main()
} // end of class Kohls
This is syntactically incorrect:
NumberFormat fmt = new NumberFormat.getCurrencyInstance();
You are not newing an instance of NumberFormat. NumberFormat.getCurrencyInstance() is a method call, and hence can't be newed.
Since the method already returns a static instance of NumberFormat, go ahead and drop the new keyword from the declaration:
NumberFormat fmt = NumberFormat.getCurrencyInstance();
Remove new operator in the line. It is a static method and should be accessed in a static away. More over, NumberFormat is an abstract class and you cannot instantiate it as well.
NumberFormat nf = NumberFormat.getCurrencyInstance();
Don't do
new NumberFormat.getCurrencyInstance();
for a static method. Do
NumberFormat.getCurrencyInstance();
This line
NumberFormat fmt = new NumberFormat.getCurrencyInstance();
should be
NumberFormat fmt = NumberFormat.getCurrencyInstance();
since getCurrencyInstance() is declared static.
Hope this helps.
You should not be using new as getCurrencyInstance() is static
Change
NumberFormat fmt = new NumberFormat.getCurrencyInstance();
to
NumberFormat fmt = NumberFormat.getCurrencyInstance();
should be an easy one. I originally was gonna do this in javascript but have to do it prior to setting to the form in my handler page. Anyway I need to make these values have 2 decimal places. Ex 219333.5888888 needs to be 219333.58. Is there a trim function or something?
form.setUnitRepairCost(Double.toString(jobPlanBean.getUnitTotalCost())); //UNIT REPAIR COST
form.setUnitMaterialCost(Double.toString(jobPlanBean.getUnitTotalMaterialCost())); //UNIT MATERIAL COST
here is the simple example to format the decimal value
import java.text.*;
public class DecimalPlaces {
public static void main(String[] args) {
double d = 1.234567;
DecimalFormat df = new DecimalFormat("#.##");
System.out.print(df.format(d));
}
}
multiply the double by 100.0 and cast this to an int then take that int and cast it to a double and divide by 100.0
int temp = (int)(longDouble*100.0);
double shortDouble = ((double)temp)/100.0;
public static void main(String[] args) {
double d = 6.3546;
DecimalFormat df = new DecimalFormat("#.##");
System.out.print(df.format(d));
}
For getting a double back and not a string:
double d = 80.123;
DecimalFormat df = new DecimalFormat("#.##");
double p = Double.parseDouble(df.format(d));
How about:
new java.text.DecimalFormat("0.00").format( yourNumber );
Here is String manipulation to truncate double value up to tow decimal places.
public static String truncateUptoTwoDecimal(double doubleValue) {
String value = String.valueOf(doubleValue);
if (value != null) {
String result = value;
int decimalIndex = result.indexOf(".");
if (decimalIndex != -1) {
String decimalString = result.substring(decimalIndex + 1);
if (decimalString.length() > 2) {
result = value.substring(0, decimalIndex + 3);
} else if (decimalString.length() == 1) {
result = String.format(Locale.ENGLISH, "%.2f",
Double.parseDouble(value));
}
}
return result;
}
return null;
}
As suggested by other you can use class DecimalFormat of java.text.DecimalFormat. We can also use DecimalFormat to round off decimal values.
Example:
import java.math.RoundingMode;
import java.text.DecimalFormat;
public class DecimalDemo {
private static DecimalFormat decimalFormatter = new DecimalFormat("#.##");
public static void main(String[] args) {
double number = 2.14159265359;
System.out.println("Original Number : " + number);
System.out.println("Upto 2 decimal : " + decimalFormatter.format(number)); //2.14
// DecimalFormat, default is RoundingMode.HALF_EVEN
decimalFormatter.setRoundingMode(RoundingMode.DOWN);
System.out.println("Down : " + decimalFormatter.format(number)); //2.14
decimalFormatter.setRoundingMode(RoundingMode.UP);
System.out.println("Up : " + decimalFormatter.format(number)); //2.15
}
}
Look into using a Decimal Format :
DecimalFormat twoDForm = new DecimalFormat("#.##");
By using those two methods you can handle all the exceptions also :
private String convertedBalance(String balance){
String convertedBalance = balance.toString();
Double d;
try {`enter code here`
d = Double.parseDouble(balance.toString());
Log.i("ConvertedNumber", "d (amount) = "+d.toString());
d = round(d, 2);
DecimalFormat f = new DecimalFormat("0.00");
convertedBalance = f.format(d);
Log.i("ConvertedNumber", "convertedBalance = "+convertedBalance);
}catch (NumberFormatException e){
Log.i("ConvertedNumber", "Number format exception");
}
return convertedBalance;
}
public static double round(double value, int places) {
if (places < 0) throw new IllegalArgumentException();
BigDecimal bd = new BigDecimal(value);
bd = bd.setScale(places, RoundingMode.HALF_UP);
return bd.doubleValue();
}
Yes, DecimalFormat: http://www.exampledepot.com/egs/java.text/FormatNum.html
DecimalFormat Class
public static double truncateDecimals(double d, int len) {
long p = pow(10, len);
long l = (long)(d * p);
return (double)l / (double)p;
}
public static long pow(long a, int b) {
long result = 1;
for (int i = 1; i <= b; i++) {
result *= a;
}
return result;
}
You can simply use String.format() as below.
double height = 175.8653;
System.out.println("Height is: " + String.format("%.2f", height));
This will trim the double value to two decimal places.
In the code, I have
int a = 62;
int b = 132;
double c;
c = (double) a/b;
System.out.println(c);
which prints out the value of c as 0.469696968793869
How can I just keep a short format for c, like 0.4697
DecimalFormat df = new DecimalFormat("#.####");
System.out.print(df.format(c));
#.#### to keep four decimal places but trailing zeros would be ignored. If you want to four decimal places including any trailing zeros, use format string #.0000 instead.
What you want is NumberFormat.
NumberFormat formatter = new DecimalFormat("0.0000");
String s = formatter.format(c);
System.out.println(s);
(The 0 symbol shows a digit or 0 if no digit present.)
See this page for more information.
Use:
System.out.format("%.4f%n", c);
Or:
DecimalFormat myFormatter = new DecimalFormat(".####");
String output = myFormatter.format(c);
System.out.println(output);
See this Java tutorial for more details.
System.out.printf("%.4f%n", c);
The correct way to keep (not print) a result of prescribed precision is to use the java.math.BigDecimal class as follows.
import java.math.BigDecimal;
import java.math.MathContext;
import java.math.RoundingMode;
public class Foo {
private static final int PRECISION = 5;
private static final MathContext MATH_CONTEXT = new MathContext(PRECISION, RoundingMode.HALF_UP);
public static void main(String... args) {
double a = 62;
double b = 132; // Doubles used to avoid integer division truncation
final BigDecimal c = new BigDecimal(a / b, MATH_CONTEXT);
System.out.println(c); // Prints 0.46970
}
}