Java format double value with german locale - java

I have the double value 1400.0 and now I want to format this value into 1.400,00 in Java.
currently I do:
double doubleValue = 1400.0
String pattern = "0.00";
DecimalFormat format = (DecimalFormat)NumberFormat.getNumberInstance(Locale.GERMAN)
format .applyPattern(pattern);
// will be 1400,00 and not 1.400,00
String formattedValue = format.format(doubleValue);
What am I missing?

Try:
String pattern = "#,##0.00";
This pattern tells a DecimalFormat to add the grouping character to the given number.
Edit: Originally I wrote this with zeros, but this would actually create extra zeros for small numbers. Use the # pattern where you don't want initial zeros.

You can try something like this:
class MyClass {
public static void main(String[] args) {
double doubleValue = 74637.96;
Locale locale = Locale.GERMAN;
String string = NumberFormat.getNumberInstance(locale).format(doubleValue);
System.out.println(string);
}
}
and the output will be:
74.637,96
GermanFormat

Related

How can I convert an implied decimal point to a real decimal point in java?

I'm trying to take a string and convert into a currency. For example I would like to take the string 12579500 and convert it to $125,795.00. I am trying to use DecimalFormat("$#,###.00), to convert the string after I turn it into a double, but what I'm winding up with is $12,579,500.00.
How do I set the last 2 numbers at the end of the string to be decimal points?
Here is my code so far.
DecimalFormat df = new DecimalFormat("$#,###.00");
double ticketPriceNum = Double.parseDouble(ticketPrice);
System.out.print(df.format(ticketPriceNum));
This will make sure that your string is reduced by 2 characters
DecimalFormat df = new DecimalFormat("$#,###.00");
double ticketPriceNum = Double.parseDouble(ticketPrice.substring(0, ticketPrice.length()- 2));
System.out.print(df.format(ticketPriceNum));
try this please
public static void main(String[] args) {
DecimalFormat df = new DecimalFormat("$#,###,##.00");
//if last two digits of ticketprice should be decimal points
double ticketPriceNum = Double.parseDouble(ticketPrice/100);
System.out.println(df.format(ticketPriceNum ));
}

How to round it off a String after two decimal digits in this case?

I am using Yahoo's YQL API and fetching the global indices; the issue that I am facing is that for some of the regions I am getting values as:
String change_inpoints = "510.663757";
String change_inpercentage = "+0.095152%";
Could you please tell me how can I round it off after two digits?
Use DECIMALFORMAT.
public static void main(String[] args) {
String s = "2.22234242342342";
double d = Double.parseDouble(s);
DecimalFormat decimal = new DecimalFormat("#.00%");
System.out.println(s);
System.out.println(decimal.format(d));
}

Is it normal that is not rounding while parsing? NumberFormat

Why does it not round in the parsing process?
NumberFormat format = NumberFormat.getInstance();
System.out.println(format.getMaximumFractionDigits());// 3
System.out.println(format.getRoundingMode());// half even
Double dob = (Double)format.parse("1212.35656");
System.out.println(dob);// output is 1212.35656
The digit counts are only used for formatting. When you parse a number you always get the number that best matches the input, even if it has more digits than the NumberFormat would use to format.
To parse a number from a string and then round to a given number of fractional digits you can use BigDecimal from the java.math package:
BigDecimal bd = BigDecimal("1212.35656");
double dob = bd.setScale(3, RoundingMode.HALF_EVEN).doubleValue();
To obtain what you desire you need to call the formatter metod of the implementation NumberFormat loaded (in your case DecimalFromat); i just added the needed lines at the end and wrapped in a main:
import java.text.NumberFormat;
public class NumberFormatRounding {
public static void main(String[] args) throws Exception{
NumberFormat formatter = NumberFormat.getInstance();
System.out.println(formatter.getMaximumFractionDigits());// 3
System.out.println(formatter.getRoundingMode());// half even
Double dob = (Double) formatter.parse("1212.35656");
System.out.println(dob);// output is 1212.35656
String formattedDob = formatter.format(dob.doubleValue());
System.out.println(formattedDob);// output is 1212.357
}
}
Note that the formattedDob is a String

How to convert a string 3.0103E-7 to 0.00000030103 in Java?

How to convert a string 0E-11 to 0.00000000000 in Java? I want to display the number in non scientific notations. I've tried looking at the number formatter in Java, however I need to specific the exact number of decimals I want but I will not always know. I simply want the number of decimal places as specificed by my original number.
Apparently the correct answer is to user BigDecimal and retrieve the precision and scale numbers. Then use those numbers in the Formatter. Something similar like this:
BigDecimal bg = new BigDecimal(rs.getString(i));
Formatter fmt = new Formatter();
fmt.format("%." + bg.scale() + "f", bg);
buf.append( fmt);
Using BigDecimal:
public static String removeScientificNotation(String value)
{
return new BigDecimal(value).toPlainString();
}
public static void main(String[] arguments) throws Exception
{
System.out.println(removeScientificNotation("3.0103E-7"));
}
Prints:
0.00000030103
I would use BigDecimal.Pass your string into it as a parameter and then use String.format to represent your newly created BigDecimal without scientific notation.
Float or Double classes can be used too.
double d = Double.parseDouble("7.399999999999985E-5");
NumberFormat formatter = new DecimalFormat("###.#####");
String f = formatter.format(d);
System.out.println(f); // output --> 0.00007
I haven't tried it, but java.text.NumberFormat might do what you want.

Convert a String to Double - Java

What is the easiest and correct way to convert a String number with commas (for example: 835,111.2) to a Double instance.
Thanks.
Have a look at java.text.NumberFormat. For example:
import java.text.*;
import java.util.*;
public class Test
{
// Just for the sake of a simple test program!
public static void main(String[] args) throws Exception
{
NumberFormat format = NumberFormat.getInstance(Locale.US);
Number number = format.parse("835,111.2");
System.out.println(number); // or use number.doubleValue()
}
}
Depending on what kind of quantity you're using though, you might want to parse to a BigDecimal instead. The easiest way of doing that is probably:
BigDecimal value = new BigDecimal(str.replace(",", ""));
or use a DecimalFormat with setParseBigDecimal(true):
DecimalFormat format = (DecimalFormat) NumberFormat.getInstance(Locale.US);
format.setParseBigDecimal(true);
BigDecimal number = (BigDecimal) format.parse("835,111.2");
The easiest is not always the most correct. Here's the easiest:
String s = "835,111.2";
// NumberFormatException possible.
Double d = Double.parseDouble(s.replaceAll(",",""));
I haven't bothered with locales since you specifically stated you wanted commas replaced so I'm assuming you've already established yourself as a locale with comma is the thousands separator and the period is the decimal separator. There are better answers here if you want correct (in terms of internationalization) behavior.
Use java.text.DecimalFormat:
DecimalFormat is a concrete subclass
of NumberFormat that formats decimal
numbers. It has a variety of features
designed to make it possible to parse
and format numbers in any locale,
including support for Western, Arabic,
and Indic digits. It also supports
different kinds of numbers, including
integers (123), fixed-point numbers
(123.4), scientific notation (1.23E4),
percentages (12%), and currency
amounts ($123). All of these can be
localized.
A link can say more than thousand words
// Format for CANADA locale
Locale locale = Locale.CANADA;
String string = NumberFormat.getNumberInstance(locale).format(-1234.56); // -1,234.56
// Format for GERMAN locale
locale = Locale.GERMAN;
string = NumberFormat.getNumberInstance(locale).format(-1234.56); // -1.234,56
// Format for the default locale
string = NumberFormat.getNumberInstance().format(-1234.56);
// Parse a GERMAN number
try {
Number number = NumberFormat.getNumberInstance(locale.GERMAN).parse("-1.234,56");
if (number instanceof Long) {
// Long value
} else {
// Double value
}
} catch (ParseException e) {
}
There is small method to convert german price format
public static BigDecimal getBigDecimalDe(String preis) throws ParseException {
NumberFormat nf = NumberFormat.getInstance(Locale.GERMAN);
Number number = nf.parse(preis);
return new BigDecimal(number.doubleValue());
}
----------------------------------------------------------------------------
German format BigDecimal Preis into decimal format
----------------------------------------------------------------------------
public static String decimalFormat(BigDecimal Preis){
String res = "0.00";
if (Preis != null){
NumberFormat nf = NumberFormat.getInstance(Locale.GERMANY);
if (nf instanceof DecimalFormat) {
((DecimalFormat) nf).applyPattern("###0.00");
}
res = nf.format(Preis);
}
return res;
}
---------------------------------------------------------------------------------------
/**
* This method converts Deutsche number format into Decimal format.
* #param Preis-String parameter.
* #return
*/
public static BigDecimal bigDecimalFormat(String Preis){
//MathContext mi = new MathContext(2);
BigDecimal bd = new BigDecimal(0.00);
if (!Util.isEmpty(Preis)){
try {
// getInstance() obtains local language format
NumberFormat nf = NumberFormat.getInstance(Locale.GERMAN);
nf.setMinimumFractionDigits(2);
nf.setMinimumIntegerDigits(1);
nf.setGroupingUsed(true);
java.lang.Number num = nf.parse(Preis);
double d = num.doubleValue();
bd = new BigDecimal(d);
} catch (ParseException e) {
e.printStackTrace();
}
}else{
bd = new BigDecimal(0.00);
}
//Rounding digits
return bd.setScale(2, RoundingMode.HALF_UP);
}

Categories