Formatting Double with two dp - java

From my decimalForm method below, i want to convert double value 7777.54 to 7 777,54 but i am getting 7 777 54. what have missed ? result should be 7 777,54
public static String decimalForm(double value){
DecimalFormat df = new DecimalFormat("#,###,###.00");
String formatted_value = df.format(value).replaceAll(",", " ").replace(".", ",");
return formatted_value;
}

This works for me:
DecimalFormat df = new DecimalFormat("#,###,###.00");
String formatted_value = df.format(value).replaceAll("\\.", " ");
In fact i tried to print out df.format(value) and, with value=95871 i got 95.871,00

you can use
String formatted_value = String.format("$%.2f", value);

In the pattern #,###,###.00, . is the decimal separator and , is the group separator. The character used for this two separators depends on your locale.
For example, if you are french, df.format(value) will equals to 7 777,54.

This is no String.replace version
DecimalFormat df = new DecimalFormat("#,###,###.00", new DecimalFormatSymbols(Locale.FRANCE));
String s = df.format(7777.54);
System.out.println(s);
output
7 777,54

Related

Java Decimal Format parsing issue

public class NumFormatTest
{
public static void main(String[] args) throws ParseException
{
String num = "1 201";
DecimalFormat df = (DecimalFormat) NumberFormat.getNumberInstance(Locale.FRANCE);
System.out.println("Number Before parse: "+num);
double dm = df.parse(num).doubleValue();
System.out.println("Number After parse: "+dm);
}
}
Output:
Number Before parse: 1 201
Number After parse: 1.0
Expected Output:
Number Before parse: 1 201
Number After parse: **1201**
Can any please help me understand why parse is not able to convert a FRENCH locale formatted string (1 201) to normal double value (1201.0)?
There are two kinds of spaces. The "normal" space character (No. 32 - HEX 0x20) and the non-breaking space (NBSP) (No. 160 - HEX 0xA0).
The French locale expects the whitespace character between the digits to be the non breaking space! You can help yourself with this line of code:
String num = "1 201";
num = num.replaceAll(" ", "\u00A0"); // '\u00A0' is the non breaking whitespace character!
This way your code will work like expected. Please note that if you format a double into a String with French locale the resulting whitespace character will be the NBSP too!!!
DecimalFormat df = (DecimalFormat) NumberFormat.getNumberInstance(Locale.FRENCH);
System.out.println(df.format(1201.1));
// This will print "1 202,1" But the space character will be '\u00A0'!
You can use
String num = "1 201";
DecimalFormat df = (DecimalFormat) NumberFormat.getNumberInstance(Locale.FRANCE);
System.out.println("Number Before parse: "+num);
DecimalFormatSymbols symbols = df.getDecimalFormatSymbols();
symbols.setGroupingSeparator(' ');
df.setDecimalFormatSymbols(symbols);
double dm = df.parse(num).doubleValue();
System.out.println("Number After parse: "+dm);
Expected Output:
Number Before parse: 1 201
Number After parse: 1201.0
Actually, Java is using the character unbreakable space (\u00a0) to parse French numbers.
Thus, the following code actually works:
String num = "1\u00a0201";
double dm = df.parse(num).doubleValue();
System.out.println("Number After parse: " + dm);
See #ParkerHalo answer which provide more details.
This seems to work.
public double parse(String decimalAsText) {
NumberFormat decimalFormat = NumberFormat.getNumberInstance(Locale.FRANCE);
decimalAsText = decimalAsText.replace(' ', '\u00a0');
ParsePosition pp = new ParsePosition(0);
Number n = decimalFormat.parse(decimalAsText, pp);
return n.doubleValue();
}

Regex to format a string in a valid big decimal value

Dear friends I'reading a csv file that contains some file like this 1.086,12. Now my problem is that I have to format it a way that allows my to create a BigDecimal, them my correct value should be 1086.12. But I could also have another value 99,11 and in this case I have to get 99.11.
I write this snippet of code:
BigDecimal bigDecimal = null;
String str = value.replace(',','.');
bigDecimal = new BigDecimal(str);
My code works just in the latter cese, Is there some regular expression that allows this?
You do not need a regex. You can/should use DecimalFormat for that:
DecimalFormatSymbols dfs = new DecimalFormatSymbols(Locale.GERMAN);
DecimalFormat df= new DecimalFormat();
df.setDecimalFormatSymbols(dfs);
Double valCEWithUKFormat = df.parse(str).doubleValue();
You can use this Java code:
String[] arr = {"1.086,12", "99.11"};
for (String tok: arr) {
if (tok.matches("[^.]*\\.[^,]+,.*"))
tok= tok.replace(".", "").replace(",", ".");
System.out.println( tok );
}
output:
1086.12
99.11

Removing trialing zeros from String?

I have a java web service which returns a list of strings type result as below.
12341.0
4578231.0
25.0
4785555.0
347895666.0
Now how can I remove trialing zeroes? what I want is list of strings as:
12341
4578231
25
4785555
347895666
how can i do it?
Try this, this is what I used using regex.
result = result.indexOf(".") < 0 ? result : result.replaceAll("0*$", "").replaceAll("\\.$", "");
or use Decimal Format
String result = "347895666.0";
DecimalFormat decimalFormat = new DecimalFormat("###.#");
String result = decimalFormat.format(Double.valueOf(s));
System.out.println(result);
class Test
{
public static void main(String[] args) throws ParseException {
Number parse = NumberFormat.getNumberInstance().parse("12341.0");
System.out.print(parse);
}
}
Use regex:
str = str.replaceAll("\\.0+$", "");
It may help :
string.replaceFirst("[.]0*$","")
You can use the substring (Java 7) or substring (Java 8) method in Java.
String result = "12341.0";
String stripped = result.substring(0, result.indexOf("."));
Use decimal format...
Double num= Double.parseDouble("1.300");
DecimalFormat format = new DecimalFormat("0.#");
System.out.println(format.format(num));
output: 1.3
If you are getting double from the web service you can use this
System.out.println((int)Double.parseDouble("12341.0"));

Formating a number to two decimals without rounding up and converting to Double

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"
}
}

Number/Currency Formatting

I do have Bulgarian currency in a format like +000000027511,00.I want to convert this format to 27511.00,I have tried it and got using substring combinations and regex,Is there any patterns or regex to do it in more simplified way?
Implementation I tried,
String currency= "+000000027511"; // "[1234]" String
String currencyFormatted=currency.substring(1);
System.out.println(currencyFormatted.replaceFirst("^0+(?!$)", ""));
Using Double.valueOf + DecimalFormat.format, or DecimalFormat.parse + format, or BigDecimal you can do it as this.
// method 1 (parsing to Float)
String s = "+000000027511,00".replace(",", ".");
Double f = Double.valueOf(s);
DecimalFormat df = new DecimalFormat("#########0.00");
String formatted = df.format(f);
System.out.println(formatted);
// method 2 (parsing using Decimal Format)
s = "+000000027511,00";
DecimalFormat df2 = new DecimalFormat("+#########0.00;-#########0.00");
Number n = df2.parse(s);
df = new DecimalFormat("#########0.00");
formatted = df.format(n);
System.out.println(formatted);
// method 3 (using BigDecimal)
BigDecimal b = new BigDecimal(s.replace(",", "."));
b.setScale(2, RoundingMode.HALF_UP);
System.out.println(b.toPlainString());
Will print
27511.00
27511.00
27511.00
Something like this:
String s = "+000000027511,00";
String r = s.replaceFirst("^\\+?0*", "");
r = r.replace(',', '.');
Try
String s = "+000000027511,00";
s = s.replace("+", "").replaceAll("^0+", "").replace(',', '.');
System.out.println(s);

Categories

Resources