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
Related
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"));
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"
}
}
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
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);
I am using NumberFormat.getCurrencyInstance(myLocale) to get a custom currency format for a locale given by me. However, this always includes the currency symbol which I don't want, I just want the proper currency number format for my given locale without the currency symbol.
Doing a format.setCurrencySymbol(null) throws an exception..
The following works. It's a bit ugly, but it fulfils the contract:
NumberFormat nf = NumberFormat.getCurrencyInstance();
DecimalFormatSymbols decimalFormatSymbols = ((DecimalFormat) nf).getDecimalFormatSymbols();
decimalFormatSymbols.setCurrencySymbol("");
((DecimalFormat) nf).setDecimalFormatSymbols(decimalFormatSymbols);
System.out.println(nf.format(12345.124).trim());
You could also get the pattern from the currency format, remove the currency symbol, and reconstruct a new format from the new pattern:
NumberFormat nf = NumberFormat.getCurrencyInstance();
String pattern = ((DecimalFormat) nf).toPattern();
String newPattern = pattern.replace("\u00A4", "").trim();
NumberFormat newFormat = new DecimalFormat(newPattern);
System.out.println(newFormat.format(12345.124));
Set it with an empty string instead:
DecimalFormat formatter = (DecimalFormat) NumberFormat.getCurrencyInstance(Locale.US);
DecimalFormatSymbols symbols = formatter.getDecimalFormatSymbols();
symbols.setCurrencySymbol(""); // Don't use null.
formatter.setDecimalFormatSymbols(symbols);
System.out.println(formatter.format(12.3456)); // 12.35
The given solution worked but ended up lefting some whitespaces for Euro for example.
I ended up doing :
numberFormat.format(myNumber).replaceAll("[^0123456789.,]","");
This makes sure we have the currency formatting for a number without the currency or any other symbol.
Just use NumberFormat.getInstance() instead of NumberFormat.getCurrencyInstance() like follows:
val numberFormat = NumberFormat.getInstance().apply {
this.currency = Currency.getInstance()
}
val formattedText = numberFormat.format(3.4)
I still see people answering this question in 2020, so why not
NumberFormat nf = NumberFormat.getInstance(Locale.US);
nf.setMinimumFractionDigits(2); // <- the trick is here
System.out.println(nf.format(1000)); // <- 1,000.00
Maybe we can just use replace or substring to just take the number part of the formatted string.
NumberFormat fmt = NumberFormat.getCurrencyInstance(Locale.getDefault());
fmt.format(-1989.64).replace(fmt.getCurrency().getSymbol(), "");
//fmt.format(1989.64).substring(1); //this doesn't work for negative number since its format is -$1989.64
DecimalFormat df = new DecimalFormat();
df.setMinimumFractionDigits(2);
String formatted = df.format(num);
Works with many types for num, but don't forget to represent currency with BigDecimal.
For the situations when your num can have more than two digits after the decimal point, you could use df.setMaximumFractionDigits(2) to show only two, but that could only hide an underlying problem from whoever is running the application.
Most (all?) solutions provided here are useless in newer Java versions. Please use this:
DecimalFormat formatter = (DecimalFormat) DecimalFormat.getCurrencyInstance(Locale.forLanguageTag("hr"));
formatter.setNegativeSuffix(""); // does the trick
formatter.setPositiveSuffix(""); // does the trick
formatter.format(new BigDecimal("12345.12"))
Two Line answer
NumberFormat formatCurrency = new NumberFormat.currency(symbol: "");
var currencyConverted = formatCurrency.format(money);
In TextView
new Text('${formatCurrency.format(money}'),
NumberFormat numberFormat = NumberFormat.getCurrencyInstance(Locale.UK);
System.out.println("getCurrency = " + numberFormat.getCurrency());
String number = numberFormat.format(99.123452323232323232323232);
System.out.println("number = " + number);
here the code that with any symbol (m2, currency, kilos, etc)
fun EditText.addCurrencyFormatter(symbol: String) {
this.addTextChangedListener(object: TextWatcher {
private var current = ""
override fun afterTextChanged(s: Editable?) {
}
override fun beforeTextChanged(s: CharSequence?, start: Int, count: Int, after: Int) {
}
override fun onTextChanged(s: CharSequence?, start: Int, before: Int, count: Int) {
if (s.toString() != current) {
this#addCurrencyFormatter.removeTextChangedListener(this)
val cleanString = s.toString().replace("\\D".toRegex(), "")
val parsed = if (cleanString.isBlank()) 0.0 else cleanString.toInt()
val formatter = DecimalFormat.getInstance()
val formated = formatter.format(parsed).replace(",",".")
current = formated
this#addCurrencyFormatter.setText(formated + " $symbol")
this#addCurrencyFormatter.setSelection(formated.length)
this#addCurrencyFormatter.addTextChangedListener(this)
}
}
})
}
-use with-
edit_text.addCurrencyFormatter("TL")
In a function like this
fun formatWithoutCurrency(value: Any): String {
val numberFormat = NumberFormat.getInstance()
return numberFormat.format(value)
}
there is a need for a currency format "WITHOUT the symbol", when u got huge reports or views and almost all columns represent monetary values, the symbol is annoying, there is no need for the symbol but yes for thousands separator and decimal comma.
U need
new DecimalFormat("#,##0.00");
and not
new DecimalFormat("$#,##0.00");
Please try below:
var totale=64000.15
var formatter = new Intl.NumberFormat('de-DE');
totaleGT=new Intl.NumberFormat('de-DE' ).format(totale)