This question already has answers here:
How do I format a number in Java?
(9 answers)
Closed 5 years ago.
How do I format a string with commas to display in curreny format?
Assume the incoming string is a big number. For example:
"1234567901234567890123456"
I want result as:
"12,345,678,901,234,567,890,123,456"
The DecimalFormat in Java has a limitation to format a big number.
95% of problems are solved by clarifying your requirements. Let's filter out the things that are definitely not requirements. "incoming string is a big number" - that statement can never hold true. Is it a String? If yes, then it's a String, and never a number. This distinction is important. I'll assume that the answer to this question is "yes".
Now that you have a String, why are you using a DecimalFormat? What does a String have to do with a decimal number formatter? Nothing related to the problem that you are trying to solve. I'll leave the determination of the correct approach to solve your problem up to you - after all, my speculations at your requirements may not be correct.
To reiterate, here are the things that are definitely incorrect:
- You have a String, that is a big number"
- DecimalFormat has an issue with "big numbers" - an unsubstantiated conclusion drawn on a false basis of understanding.
System.out.println(NumberFormat.getNumberInstance(Locale.US).format(35634646));
Output: 35,634,646
This would do
double formatThis = Double.parseDouble(yourNumber);
DecimalFormat formatter = new DecimalFormat("#,###.00");
System.out.println(formatter.format(formatThis));
You should be able to achieve the desired using the expression posted below:
(?n:(^\$?(?!0,?\d)\d{1,3}(?=(?<1>,)|(?<1>))(\k<1>\d{3})*(\.\d\d)?)$)
Try this.
String input = "12345678901234567890123456";
String output = String.format("%,d", new BigInteger(input));
System.out.println(output);
// -> 12,345,678,901,234,567,890,123,456
Related
This question already has answers here:
Java BigDecimal can have comma instead dot?
(3 answers)
Closed 3 months ago.
I have a method to set a BigDecimal number that is given as String:
private Client mapClient(Client client){
ClientRequest clientRequest = new ClientRequest();
// Code
clientRequest.setCashAmount(castStringToBigDecimal(client.getCashAmount()));
// More Code
}
My castStringToBigDecimal method is the follosing:
public BigDecimal castStringToBigDecimal(String value){
BigDecimal response = null;
if(value != null && !value.equals("")){
value = value.replaceAll("[.]", ",");
response = new BigDecimal(value);
}
return response;
}
An example of the input value is "1554.21"
I need that the bigDecimal separator to be a comma, not a dot. But this is giving me an exception.
EDIT
The value is the following:
And the exception is:
java.lang.NumberFormatException: Character , is neither a decimal digit number, decimal point, nor "e" notation exponential mark.
BigDecimal doesn't represent a rendering. In other words, whether to use a comma or a dot as separator is not part of the properties a BigDecimal object has.
Hence, you do not want to call .replaceAll. (And separately, you'd want .replace(".", ",") - replace replaces all, and replaceAll also replaces all and interprets the first arg as a regex, and is therefore needlessly confusing here). Just pass it with the dot.
To render a BigDecimal, don't just sysout it, that will always show a dot and there is nothing you can do about that. toString() is almost never the appropriate tool for the job of rendering data to a user - it's a debugging aid, nothing more. Use e.g. String.format("%f"), specifying the appropriate locale. Or use NumberFormat. The javadoc of BigDecimal explicitly spells this out.
There are various other issues with your code:
"cast" is the technical name for the syntactic construct: (Type) expr; - and this construct does 3 utterly different things, hence using it to describe a task, i.e. use it in a method name, is a very bad idea. In particular, only one of the 3 things it does converts anything, and you clearly use it here in the 'convert something' meaning. This is misleading; only if it's all primitives does the cast operator convert, and BigDecimal isn't primitive. Call it convertTo or whatever you please, not "cast".
BigDecimal is an extremely complicated tool for the job and usually not the right tool if you want to represent financial data. Instead, represent the atomary unit in a long and call the appropriate rendering method whenever you need to show it to a user. For example, for euros, the atomary unit is the eurocent. If something costs €1,50, you'd store "150", in a long. Before you think: But, wait, I want to divide, and then I'd lose half a cent! - yes, well, you can't exactly send your bank a request to transfer half a cent, either. Also, try to divide 4 cents by 3 with a BigDecimal and see what happens. Dividing financial amounts is tricky no matter what you use, BD isn't a catch-all solution to this problem.
I looked up the source code for Java 8's implementation of BigDecimal (https://github.com/frohoff/jdk8u-dev-jdk/blob/master/src/share/classes/java/math/BigDecimal.java), and the period character is hard-coded in that source as the decimal point. I would not have thought this of a language for which internationalization has been so thoroughly designed in, but there it is, line 466.
Given that the author(s) of BigDecimal failed to take locale into account in such a basic way -- the use of comma instead of period as the decimal separator in Europe is well-known -- I'd have to say you cannot use that BigDecimal constructor on unaltered Strings that are otherwise formatted correctly but which (might) have a comma separator. There are other options -- the previous SO post referred to in one of the comments has one -- but it appears you cannot convert your String this way.
(One minor point -- you are not "casting" anything. That word has a specific meaning in OO programming, and a more specific one in Java, and has very little to do with your question. It is incorrect to refer to conversion as casting.)
This question already has answers here:
How can I format a String number to have commas and round?
(11 answers)
Closed 4 years ago.
Let's say I have a String variable that looks like this.
String milli = "2728462" is there a way to convert it to look something like this
2,252,251 which I guess I want as a long.
The thing is it will be passing strings in this format
1512
52
15010
1622274628
and I want it to place the , character where it needs, so if the number is 1000 then place it like so 1,000 and 100000 then 100,000 etc.
How do I properly convert a String variable like that?
Because this
String s="9990449935";
long l=Long.parseLong(s);
System.out.println(l);
Will output 9990449935 and not 9,990,449,935
Basic strategy for is to convert string representation of the number to the one of Number format. Then you have following options to represent this number according to the give Locale.
String.format()
System.out.format(Locale.US, "%,d", Long.parseLong("2728462"));
NumberFormat
System.out.println(NumberFormat.getNumberInstance(Locale.US).format(Long.parseLong("2728462")));
You can try
String milli = "2728462"
System.out.println(NumberFormat.getInstance(Locale.US).format(Long.parseLong(milli)));
This question already has answers here:
How to evaluate a math expression given in string form?
(26 answers)
Closed 6 years ago.
i have a string with a math function, like "35+20". i want a new double variable that takes in the result of the math function i.e, 55.0 How do i achieve this? this is actually for android, i'm making a calculator..
Manually parse the string and do a calculation at each operator symbol. It will get more complicated when dealing with brackets, however.
If you want to write it yourself, you'll probably want to implement the Shunting Yard Algorithm.
There are also some libraries that handle it for you.
https://github.com/uklimaschewski/EvalEx
Since you have mentioned you are working on a calculator I am assuming that you might not only be interested in just the + operation but on a bunch of other stuffs too.
You can look in to open source GitHub project linked below which provides the JAVA implementation for the stuff you are trying to do https://github.com/uklimaschewski/EvalEx
which can give you a good set of functionality that you desire.
This project takes in a string as an expression and the returns the result in BigDecimal format.
You can always extend it and tweek it to custom suite you needs.
This question already has answers here:
Is there a good reason to use "printf" instead of "print" in java?
(4 answers)
Closed 9 years ago.
When is it considered good code to format a string output like this:
int count = 5;
double amount = 45.6;
System.out.printf("The count is %d and the amount is %45.6", count, amount);
utilising a printf statement, over code like this:
int count = 5;
double amount = 45.6;
System.out.print("The count is " + count + "and the amount is " + amount);
using a print statement?
I have read the JavaDocs which state that printf is "A convenience method to write a formatted string to this output stream using the specified format string and arguments."
But it doesn't state when, by convention, we should use one over the other?
So, when is it good coding to use a printf, and when is it good coding not to?
Thanks for any help.
Two methods are provided for the convenience of a coder and for different needs. If you need string formatting then go for printf method but if there is no formatting required simply use print method and void %d,%s, etc formatters.
If you want to control the precision & padding of floating point numbers then use printf otherwise go for print.
printf was added quite recently in the history of java as a convenience because so many people were used to C style printf and what it could do. so one isnt really better or preferred over the other. Regular "print" style though is clearer and simpler when special printf formatting isnt required.
Hello and thank you in advance for the help.
I am having some trouble formatting using a Java function to mark up a price in HTML.
It seems that, no matter what I do, I cannot insert custom content between the numbers and the decimal (throws Illegal Argument Exception). Is there any known way to achieve the following:
NumberFormat nf = getNumberFormat("'<span class=\"dollars\">'##'</span></span class=\"decimal\">'.'</span></span class=\"cents\">'00'</span>'", locale);
nf.format(number);
Assume locale and number are correctly initialized.
If you look at the docs for DecimalFormat you'll see that they talk about the prefix and the suffix text - but not putting arbitrary text within a number.
It sounds like you should basically write this bit of formatting yourself - possibly using DecimalFormat for each section of the number.
You might consider using String.format(String pattern, Object... arguments). You can pass your simply formatted numbers as arguments.