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.
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.)
I'm trying to format output for user/report appeal, and there are two criteria I'm finding to be in a bit of conflict.
First, the decimal values should line up (format on "%12.10f", predicted integer value range 0-99)
Second, the decimal shouldn't trail an excessive series of zeroes.
For example, I have output that looks like
0.5252772000
0.2053628186
10.5234500000
But using a general formatting, I also end up with:
0.53260000000
0.52630000000
12.43540000000
In certain cases, and it looks kind of garbage.
Is there a simple way to solve this problem? The only solution I can come up with at the moment involves pre-interrogating the data before printing (instead of formatting it during print) which, while technically not expensive, just bugs me as being redundant data handling (ie I have to go through all data once to find the extrema of trailing zeroes to parse against it, and then set the format so that it can go through the data again to parse it)
You can set a DecimalFormat:
DecimalFormat format = new DecimalFormat("0.#");
for (float f : yourFloats){
System.out.println(format.format(f));
}
This also works on doubles.
Am having an issue with formatting currencies in Java. I am trying to format a number to be printed as currency, with all the decimal points aligned:
£ 1.23
£ 12.34
£123.45
Calling NumberFormat.getCurrencyInstance().format(n) returns a formatted string, but all the numbers are left-aligned, producing output like this:
£1.23
£12.34
£123.45
Ugly. I have read this post which presents a solution using a DecimalFormat, and as a stopgap I'm formatting my number using a DecimalFormat and prepending the currency symbol later, but I was wondering if anyone was aware of a neater way of accomplishing the same thing?
Hope that's all clear, thanks in advance for your help!
You could do:
String currencySymbol = Currency.getInstance(Locale.getDefault()).getSymbol();
System.out.printf("%s%8.2f\n", currencySymbol, 1.23);
System.out.printf("%s%8.2f\n", currencySymbol, 12.34);
System.out.printf("%s%8.2f\n", currencySymbol, 123.45);
Note: this will only work for currencies whose symbols appear before the amount.
Also be alert to the fact that doubles are not suitable for representing currency.
Try this:
final NumberFormat nf = NumberFormat.getCurrencyInstance();
nf.setMinimumIntegerDigits(3);
System.out.println(nf.format(1.23));
System.out.println(nf.format(12.34));
System.out.println(nf.format(123.45));
hi i am trying to print after dividing in string builder and printing that string builder let show me my code ,
string.append("Memomry usage:total:"+totalMemory/1024/1024+
"Mb-used:"+usageMemory/1024/1024+
" Mb("+Percentage+"%)-free:"+freeMemory/1024/1024+
" Mb("+Percentagefree+"%)");
in above code "totalmemory" and "freememory" is of double type having bytes value in point not null so i divide it by "1024" two times to get it in "Mb" and "string" is variable of string builder after using this code i am simply printing it a am getting result as shown below,
Used Memory:Memomry usage:
total:13.3125Mb-used:0.22920989990234375Mb (0.017217645063086855%)
-free:13.083290100097656Mb (0.9827823549369131%)
i want to get percentage in twodecimal place and values of used and free memory in mb like this "used:2345.25" in this pattren remember
Hopes for your suggestions
Thanks in Advance
How about String.format()?
System.out.println(String.format("output: %.2f", 123.456));
Output:
output: 123.46
Try like this
double d = 1.234567;
DecimalFormat df = new DecimalFormat("#.##");
System.out.print(df.format(d));
Using DecimalFormat, we can format the way we wanted to see.
You can use DecimalFormat to print out to two decimal places. So, to print x = 2345.2512 with two decimal places, you would write
NumberFormat f = new DecimalFormat("#.00");
System.out.println(f.format(x));
which will print 2345.25.
Even though it is possible to use NumberFormat and it's subclass DecimalFormat for this issue,
these classes provide a lot of functionality that may not be required for your application.
If the objective is just pretty printing, I would recommend using the format function of the String class. For your specific code it would look like this:
string.append(String.format("Memomry usage:total:%1.2f Mb-used:%1.2f Mb(%1.2f %%)-free:%1.2f Mb(%1.2f %%)",totalMemory/1024/1024,usageMemory/1024/1024,Percentage,freeMemory/1024/1024,Percentagefree));
If you are intending to specify a standard format in which all numbers are represented irrespective of whether they are being parsed from strings or formatted to strings, then I would recommend using singletons of the *Format classes. They allow you to use standard formats and also to pass format descriptions between methods.
Hope that helps you select the right method to use in your application.
In my web application I have a version field that take float input values. But when using values like 1000000.1 (or larger) for the version it displays like 1.0E7. i tried several methods in Float wrapper class. but result still the same.
Thanks
Your problem is not in parsing but in formatting of your values. The value is correct and it is represented in java correctly. If you wish to change the format user either String.format() that provides C style formatting or java.text.NumberFormat.
System.out.printf("%f", Float.parseFloat("1.0E7")); outputs 10000000.000000
See http://ideone.com/3o6dO
Note that 1.0E7 is 1000000.0, not 1000000.1.
it probably has to do with your output format because 1.0E7 == 10000000
I think what you are looking for is the String.format(locale, msg, args) method.
Use String.valueOf(floatNumber)
Suggest use double instead of float