Trouble with setting RoundingMode on DecimalFormat - java

This might be kind of a dumb question, but I'm stuck on it.
I'm trying to set the RoundingMode on a DecimalFormat.
DecimalFormat df = new DecimalFormat("###.##");
df.setRoundingMode(RoundingMode.HALF_UP);
However, the code looks fine to me and it looks the same as many examples I have seen.
The error on setRoundingMode() is:
***The method setRoundingMode(RoundingMode) is undefined for the type DecimalFormat***
It suggests to cast df to an Object, but that doesn't solve anything...
Any suggestions?
EDIT
I am using ver. 1.7
Below I changed the compliance level to 1.6 yet no difference.
Thank you in advance for the help!

Try System.out.println(System.getProperty("java.version")); and be sure that your jre version really is 1.6 or higher

Related

Using Julia JavaCall with Java DecimalFormat (à la MATLAB)

I don't know java and can't get JavaCall.jl to work with java.text.DecimalFormat. In MATLAB this is very simple -- just check out this link.
Reading the JavaCall.jl documentation, I tried replicating the provided example with DecimalFormat and got this far:
julia>using JavaCall
julia>JavaCall.init(["-Xmx128M"])
julia>jdf = #jimport java.text.DecimalFormat
After that, I got a bunch of errors. (bear in mind: I absolutely have no clue as to how Java works?)
Please help!
It's not clear from the question whether you're looking to know more about JavaCall.jl or just to use some comma separated formatting.
If the latter, then you can use the Formatting.jl package: https://github.com/JuliaIO/Formatting.jl
julia> using Formatting
julia> sprintf1("%'.02f", 123456789)
"123,456,789.00"
And then you don't need any Java.
This package also has a bunch of other formatting options.

Android - Invalid Double "#,##"

A user of my app is having a error and the app is crashing
I've looked at the report and it's stating
Caused by: java.lang.NumberFormatException: Invalid double: "1,36"
I have reproduced the data inputted on my app and I don't have the issue at all
I have even asked her to send me her database so i can import the exact data and it still worked okay for me
I'm confused as to where the double is getting formatted like that as I can't see anywhere in my code where it would get formatted with a ,
Any suggestions as to what's going on?
Simple way is (do it above your parce):
if (str.contains(",")) {
str.replace(",",".");
}
I just have faced the same problem. I was converting float value to String. Yes, it must be a locale issue. As said in one of the comments, Some locales use , as a decimal separator.
Initially I was converting float like-
String.format("%.1f", value);
Then I changed the code to
String.format(Locale.ENGLISH, "%.1f", value);
So, forcing the string to be converted with English local worked for me.
You seem to have encountered a locale problem. Different locales have . and , as fractional part separator. You can use java.text.NumberFormat to work with the locale you want, e.g. FRANCE for comma and US for point:
// somewhere at Utils.java:
public static final NumberFormat DOUBLE_FORMAT = NumberFormat.getInstance(Locale.FRANCE);
// at call site:
double d = Utils.DOUBLE_FORMAT.parse("1,234").doubleValue();

Understanding the strange output of java.util.Locale

I had a perception that Locale is just about adding comma at proper positions at least in case of numbers. But I see a different output for what I have tried.
I tried the following,
public static void main(String[] args) {
DecimalFormat df = null;
df = (DecimalFormat) DecimalFormat.getInstance(Locale.CHINESE);
System.out.println("Locale.CHINESE "+df.format(12345.45));
df = (DecimalFormat) DecimalFormat.getInstance(Locale.GERMAN);
System.out.println("Locale.GERMAN "+df.format(12345.45));
}
Output:
Locale.CHINESE 12,345.45
Locale.GERMAN 12.345,45
If you carefully look at the comma's, you'll see a major difference.
Now, the javadoc for java.util.Locale says
... An operation that requires a Locale to perform its task is called locale-sensitive and uses the Locale to
tailor information for the user. For example, displaying a number is a locale-sensitive operation--the number
should be formatted according to
the customs/conventions of the user's native country, region, or culture ...
I see a comma being interpreted as decimal point in another Locale, which is really a curious thing, as the value is being changed.
So, help me understand this. What exactly is Locale? Won't the drastic change in output cause major issue in code/data?
I had a perception that Locale is just about adding comma at proper positions at least in case of numbers.
No, it affects the symbols used as well, as you've seen.
So, help me understand this. What exactly is Locale? Won't the drastic change in output cause major issue in code/data?
Only if you don't use them correctly :) Machine-to-machine communication should usually not be localized; typically if you really need to use text, it's best to use US as a reasonably invariant locale.
See DecimalFormatSymbols for more details of what is locale-specific.
I see nothing wrong with the above. The German way of representing 12345.45 is 12.345,45
and the Chinese way of representing the same number is 12,345.45 .
So, help me understand this. What exactly is Locale? Won't the drastic
change in output cause major issue in code/data?
No it won't you just need to keep track of the locale of the input and how you want it formatted.

Convert to unixtime: same input, different output

Maybe this is a recurrent issue, but I need to explain my problem.
I must convert date+hour to Unix time format. I use Apache Commons Lang library, DateUtils class:
Date date = DateUtils.parseDate(strStartDateTime, new String[] { "ddMMyyyyHHmmss" });
Long dateLong = new Long(date.getTime());
Maybe Java Date class is old for this, but it seems to work fine.
But lately, I have detected that the same input, in right expected format, is returning different output in different executions.
I have been looking for a similar issue, and I have read that Java Date is old, joda-time library is recommended, etc.
It would be easy to convert with joda-time, but, why is this happening? Is reliable the code above? It's very likely I'm not taking something into account.
Any help or suggestion would be very appreciated.
Thanks in advance.
Excuse me, but finally I found the error. There was a wrong attribute definition.
It was my programming error; nothing related to time conversion. Thanks

Rounding Half Up with Decimal Format in Android

I want to set the Rounding Mode to HALF_UP on my DecimalFormat, but eclipse is telling me that setRoundingMode() is not available on the DecimalFormat class. My project properties (and the overall Eclipse properties) are using the 1.6 compiler. The developer.android.com site says that I can use either Java 5 or 6 so I'm not sure what the problem is.
import java.math.RoundingMode;
import java.text.DecimalFormat;
completedValueFormatter = NumberFormat.getNumberInstance();
DecimalFormat completedDecimalFormat = (DecimalFormat)completedValueFormatter;
completedDecimalFormat.setRoundingMode(RoundingMode.HALF_UP);
I've also tried using the android tools to generate an ant-based project, tried this code in the project and also got the same compile error. So it doesn't appear to be related to Eclipse. It seems related to the Android API.
Any suggestions?
This doesn't truly answer why I can't use the Java 6 .setRoundingMode(RoundingMode) method in DecimalFormat, but it is at least a work-around.
int numDigitsToShow = this.completedValueFormatter.getMaximumFractionDigits();
BigDecimal bigDecimal = new BigDecimal(valueToBeRounded);
BigDecimal roundedBigDecimal = bigDecimal.setScale(numDigitsToShow, RoundingMode.HALF_UP);
return this.completedValueFormatter.format(roundedBigDecimal.doubleValue());
I create a BigDecimal with the value I need to round, then I get a BigDecimal of that value with the scale set to the number of digits I need to round my values to. Then I pass that rounded value off to my original NumberFormat for conversion to String.
If anyone has a better solution, I'm all ears!
Here is what I suspect the problem is, (assuming I am reading the docs properly) and its a doozy:
According to the java.text.DecimalFormat API documentation, you are not actually getting the Runtime Implimentation of the Java 1.6 RE, but are getting an android "Enhanced Version" that clearly doesn't include the setRoundingMode, which frankly bites.
"This is an enhanced version of DecimalFormat that is based on the standard version in the RI. New or changed functionality is labeled NEW."
A weakness in Java for many many many years has been the DecimalFormat class defaulted to HALF_ROUND_UP and had no way to change that, until JVM 1.6. Pity to see Android is keeping this need to kludge alive.
So looks like we are stuck Kludging BigDecimal scale Settings to format output all over any app that needs it, instead of simply being able to rely on a formatter call alone to get the job done. Not the end of the world, but very disappointing Google.
Of course that same doc says that setRondingMode() works, so perhaps this is a all out BUG??
I guess this would be the best option
http://download.oracle.com/javase/1.4.2/docs/api/java/lang/Math.html#ceil(double)

Categories

Resources