This question already has answers here:
Format, 2 decimal places for double and 0 for integer in java
(2 answers)
Closed 6 years ago.
I would like to format a BigDecimal value according to the following rules:
25 => 25
25,1 => 25,10
25,10 => 25,10
25,12 = > 25,12
I have searched the forums but not found a matching question (here, here and here) and I have looked at the javadoc for BigDecimal and NumberFormat without understanding how to do this.
EDIT:
Today I do:
NumberFormat currencyFormat02 = NumberFormat.getCurrencyInstance(locale);
currencyFormat02.setMinimumFractionDigits(0);
currencyFormat02.setMaximumFractionDigits(2);
currencyFormat02.setGroupingUsed(false);
BigDecimal bd = new BigDecimal("25 or 25,1 or 25,10 or 25,12");
String x =currencyFormat02.format(bd);
x should print as above but does not.
Probably not the most efficient but you could try something like this:
import java.math.BigDecimal;
import java.text.DecimalFormat;
import java.text.DecimalFormatSymbols;
import java.util.Locale;
class Main {
public static void main(String[] args) {
BigDecimal ex1 = new BigDecimal("25");
BigDecimal ex2 = new BigDecimal("25.1");
BigDecimal ex3 = new BigDecimal("25.10");
BigDecimal ex4 = new BigDecimal("25.12");
printCustomBigDecimalFormat(ex1);
printCustomBigDecimalFormat(ex2);
printCustomBigDecimalFormat(ex3);
printCustomBigDecimalFormat(ex4);
}
public static void printCustomBigDecimalFormat(BigDecimal bd) {
DecimalFormatSymbols symbols = new DecimalFormatSymbols(Locale.getDefault());
symbols.setDecimalSeparator(',');
DecimalFormat df = new DecimalFormat("##.00", symbols);
if(containsDecimalPoint(bd)) {
System.out.println(df.format(bd));
} else {
System.out.println(bd);
}
}
private static boolean containsDecimalPoint(BigDecimal bd) {
return bd.toString().contains(".");
}
}
Output:
25
25,10
25,10
25,12
Try it here!
You then need to distinguish between BigDecimal values that represent "whole numbers"; and those that do not.
Something like:
BigDecimal someNumber = ...
if (someNumber.toBigIntegerExact()) {
// go for the 25 kind of formatting
} else {
// go for the 25.xx kind of formatting
The "25.xx" formatting is nicely described here ( or in the other answer by Leonardo )
To format BigDecimal with NumberFormat, you need to set Locale first, try something like this:
String strToFormat = "25.10";
Locale loc = new Locale("en","US");
DecimalFormat numFormat = (DecimalFormat)NumberFormat.getInstance(loc);
numFormat.setParseBigDecimal(true);
BigDecimal yourValue = (BigDecimal)numFormat.parse(strToFormat, new ParsePosition(0));
System.out.println("Value : " + yourValue);
Result :
Value : 25.10
Related
I am struggling with formatting numbers in java.
My input format looks like this (and I cannot change that): 2.000,15
and the output should look like this: 2000.15
In case of only 0 after the comma the output should look like this: 2000
The input is given as a String.
I've already tried to use a DecimalFormat but this only leads to IllegalArgumentException
DecimalFormat decimalFormat = (DecimalFormat) NumberFormat.getInstance(Locale.ENGLISH);
decimalFormat.setMinimumFractionDigits(0);
decimalFormat.setMaximumFractionDigits(2);
decimalFormat.setGroupingUsed(false);
return decimalFormat.format(Double.parseDouble(characteristicValue));
give this a try:
NumberFormat fmt = NumberFormat.getInstance(Locale.GERMAN);
try {
BigDecimal bd = new BigDecimal(fmt.parse("2.000,15").toString());
System.out.println(bd.toString()); // output: 2000.15
} catch (ParseException e) {
//ex handling
}
You can try the following:
Choose a number format that uses dot-separated thousands-place separators.
Set the minimum significant figures for the decimal (fraction) place.
There is no need to set-up a format that already exists in Java's SDK.
import java.text.NumberFormat;
import java.text.ParseException;
import java.util.Locale;
public class FormattingNumbers {
static NumberFormat inputFormat = NumberFormat.getNumberInstance(Locale.GERMAN);
static NumberFormat outputFormat = NumberFormat.getNumberInstance(Locale.US);
static {
inputFormat.setMinimumFractionDigits(2);
outputFormat.setMinimumFractionDigits(2);
}
public static void main(String[] args) throws ParseException {
String[] numbers = { "2.000,00", "2.000,15" };
for (String number : numbers) {
System.out.println(outputFormat.format(inputFormat.parse(number)));
}
}
}
Output:
2,000.00
2,000.15
Note: Here is a list of countries using decimal comma.
You had the right tool, but you don't need to get an instance of DecimalFormat, you can just create your own.
import java.text.DecimalFormat;
class Playground {
public static void main(String[ ] args) {
String pattern = "###,###.###";
DecimalFormat decimalFormat = new DecimalFormat(pattern);
String format = decimalFormat.format(2000.15);
System.out.println(format);
}
}
This question already has answers here:
Number formatting in java to use Lakh format instead of million format
(3 answers)
Closed 6 years ago.
Input value
double value = 668260.10;
Output should be: 6,68,260.10.
I tried the below, but its doing 668,260.10 instead:
NumberFormat nf = NumberFormat.getNumberInstance(loc);
DecimalFormat df = (DecimalFormat)nf;
df.applyPattern("#,##,###.00");
String output = df.format(value);
System.out.println(output);
(Note: The separator style is as described in this Wikipedia article.)
NumberFormat doesn't support this kind of formatting.
You need to define custom formating like below
public class Test {
public static void main(String[] args) {
DecimalFormat formatter = new DecimalFormat("#,##,##0.00");
System.out.println(formatLakh(668260.10));
}
private static String formatLakh(double d) {
String s = String.format(Locale.UK, "%1.2f", Math.abs(d));
s = s.replaceAll("(.+)(...\\...)", "$1,$2");
while (s.matches("\\d{3,},.+")) {
s = s.replaceAll("(\\d+)(\\d{2},.+)", "$1,$2");
}
return d < 0 ? ("-" + s) : s;
}
}
This question already has answers here:
Best way to parseDouble with comma as decimal separator?
(10 answers)
Closed 7 years ago.
I have a string.
String value = "The value of this product: 13,45 USD";
I want it to be a double which should be like:
double actualprice=13,45;
Or should i use float, double is useless here? Sorry, i am not an expert.
So how can i transform this string to a number?
oh and i almost forgot, i've got a code, which makes it to "13,45" but it's still a String.
String price = "The price is: 13.45";
String s = price;
for(int b=0;b<s.length();b++){
if(s.charAt(b)=='.') {
System.out.print(",");
}
if(Character.isDigit(s.charAt(b))) {
System.out.print(s.charAt(b)+"");
}
}
This code will work. It will throw a NumberFormatException if the string formatted in different manner and number was not found.
double actualprice = Double.parseDouble(
value.replaceFirst("The value of this product: (\\d+),(\\d+) USD", "$1.$2"));
System.out.println(actualprice);
This may be helpful.
public class RegexTest1 {
public static void main(String[] args) {
Pattern p = Pattern.compile("\\d+,\\d+");
Matcher match = p.matcher("The value of this product: 13,45 USD");
Double d ;
while (match.find()) {
System.out.println(match.group());
DecimalFormat df = new DecimalFormat();
DecimalFormatSymbols symbols = new DecimalFormatSymbols();
symbols.setDecimalSeparator(',');
symbols.setGroupingSeparator(' ');
df.setDecimalFormatSymbols(symbols);
try {
d = (Double)df.parse(match.group());
System.out.println(d);
} catch (ParseException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
I know this has been questioned alot of times but i tried all solutions in other threads and i cant find one that matches what i want ...
So i have one input something like this -9.22841 which is read as a String, what i want to do is to format this number to two decimals like this -9.23 without rounding it up and then converting it to double without losing this format...
I have tried many ways like String.format("%.2f",number) and the one below ...
String l = -9.22841
DecimalFormat df = new DecimalFormat("#,00");
String tmp =df.format(l);
double t = Double.parseDouble(tmp);
and this one:
String l = -9.22841
DecimalFormat df = new DecimalFormat("#.00");
String tmp =df.format(l);
double t = Double.parseDouble(tmp);
but everytime i try to convert to double in the String.format("%.2f",number) or DecimalFormat df = new DecimalFormat("#.00"); gives error converting to double
and when i do this :
DecimalFormat df = new DecimalFormat("#,00");
The output is wrong and is something like this -9.23 where it should be -9.22
Thanks for your time ...
You could just chop off the String two spaces after the decimal:
String number = "-9.22841";
String shorterNumber = number.substring(0, number.indexOf(".")+3);
double t = Double.parseDouble(shorterNumber);
System.out.println(t);
Thats what you want:
String number = "-9.22841";
DecimalFormat formatter = new DecimalFormat("0.00");
formatter.setRoundingMode(RoundingMode.DOWN);
number = formatter.format(Double.valueOf(number));
System.out.println(number);
The output will be:
-9,22
You can use bellow function:
import java.text.DecimalFormat;
import java.math.RoundingMode;
public static double formatValue(Double number) {
DecimalFormat df = new DecimalFormat("####0.00");
df.setRoundingMode(RoundingMode.DOWN);
return Double.parseDouble(df.format(number));
}
Input = 31.6227890 ,
OutPUT = 31.62
For someone looking full decimal handling:Kotlin
fun validateNumber(number: String): String {
return if (number.contains(".") && number.length > 3+number.indexOf("."))
number.substring(0, number.indexOf(".")+3)
else if (number.contains(".")){
number.substring(0, number.indexOf(".")+2)+"0"
}else{
"$number.00"
}
}
I have to convert a German locale formatted String to a BigDecimal. However, I'm struggling with the best solution.
The following code shows my problem:
String numberString = "2.105,88";
NumberFormat nf = NumberFormat.getInstance(Locale.GERMAN);
try {
Number parsed = nf.parse(numberString);
BigDecimal bd1 = new BigDecimal(parsed.toString());
System.out.println(bd1.toString());
BigDecimal bd2 = new BigDecimal(parsed.doubleValue());
System.out.println(bd2);
BigDecimal bd3 = new BigDecimal(numberString);
System.out.println(bd3);
} catch (ParseException e) {
e.printStackTrace();
}
The outpout of this is
2105.88
2105.8800000000001091393642127513885498046875
Exception in thread "main" java.lang.NumberFormatException
at java.math.BigDecimal.(Unknown Source)
at java.math.BigDecimal.(Unknown Source)
at test.BigDecimalTest.main(BigDecimalTest.java:22)
The first output is correct, but it doesn't really make sense to convert a String to a Number (Double to be precise), then back to a String again and then into a specific type of Number, BigDecimal.
The second output is incorrect, but could be solved by setting the scale of the BigDecimal. However, the amount of digits is not always known.
The third output is obviously not what I'm looking for.
My question: What would be the best way? Are there better ways to do this?
It seems like there is no other way since java.Lang.Number doesn't have a method which returns a BigDecimal type. Anyway it makes sense because BigDecimal only accepts strings which are properly formatted not like "2.105,88" but like "2105.88".
Let me show your my code:
import java.math.BigDecimal;
import java.text.DecimalFormat;
import java.text.NumberFormat;
import java.text.ParseException;
import java.util.Locale;
public class JavaMain {
public static void main(String[] args) {
String numberString = "2.105,88";
//using casting
try {
DecimalFormat df = (DecimalFormat) NumberFormat.getInstance(Locale.GERMAN);
df.setParseBigDecimal(true);
BigDecimal bd = (BigDecimal) df.parseObject(numberString);
System.out.println(bd.toString());
} catch (ParseException e) {
e.printStackTrace();
}
//your way short version
NumberFormat nf = NumberFormat.getInstance(Locale.GERMAN);
try {
BigDecimal bd1 = new BigDecimal(nf.parse(numberString).toString());
System.out.println(bd1.toString());
} catch (ParseException e) {
e.printStackTrace();
}
String numberStringFixed = "2105.88";
//direct string formatted
System.out.println(new BigDecimal(numberStringFixed));;
//direct but erroneous way if the string is not formatted
System.out.println(new BigDecimal(numberString));;
}
}
I hope this helps!
DecimalFormat has a method called setParseBigDecimal that causes parse() to return a BigDecimal. You just need to cast the returned Number.
String numberString = "2.105,88";
NumberFormat nf = NumberFormat.getInstance(Locale.GERMAN);
if (nf instanceof DecimalFormat) {
DecimalFormat df = (DecimalFormat) nf;
df.setParseBigDecimal(true);
BigDecimal parsed = (BigDecimal) df.parse(numberString);
System.out.println(parsed);
}
Output:
2105.88
setParseBigDecimal was introduced in Java 1.5.