PearlJamFanatic
asked on
restrict decimal places for double datatype
I have java code that uses double type. I am using a sdk util function to round and restrict the decimal to 2 place. something like:
openCurrentBar=Util.round(localDataSeries.getOpen(paramInt), 2);
highCurrentBar=Util.round(localDataSeries.getHigh(paramInt), 2);
lowCurrentBar=Util.round(localDataSeries.getLow(paramInt), 2);
It does fix the issue temporarily but later in the code these variables show value of 11 digit decimal places again. This happens when they are used for calculation. How can I restrict the decimal paces permanently to 2 digits only such that no matter what happens in the code it does not show more than 2 digits. openCurrentBar should be something like 2365.21 and NOT 2365.213456721309.
SOLUTION
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
ASKER CERTIFIED SOLUTION
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
If you go by my third and fourth sentences, that question becomes academic
ASKER
CEHG so what you suggest is that I use the values with all the decimals for my calculation and only at the time of display I use a rounding function like the one I am using now. Is that right? will this not make debugging rather difficult? I need to think about this. I use this code to create labels for display on the chart.
buyRisk=Util.round(buyPrice-stopLossPrice, 2);
buyOpenedOnThisBar=paramInt;
Label txtLbl=new Label(new Coordinate(localDataSeries.getStartTime(paramInt),
lowCurrentBar-localDataSeries.atr(paramInt, 10)*5), "Buy @ " +buyPrice+"\nRisk= "+buyRisk+" pts");
addFigureFront(Plot.PRICE, txtLbl);
so what you suggest is that I use the values with all the decimals for my calculation and only at the time of display I use a rounding function like the one I am using now. Is that right?
Yes. If you want 2 dp then
String displayVal = String.format("%.2f", doubleValue);
Actually that's a 'yes' with the qualification that you haven't restricted the actual value's precision at all. Only what the user sees
ASKER
Ok I have made the changes in my code. I use the Util.round() at the time of display. Why do you suggest converting to string for display? why not use the SDK provided function like Util.round() which takes double and returns double. Why should it matter as it is only for display?
Because strings are more predictable. And there's less likelihood of using the imprecise value in further calculations
ASKER
Thankyou
:)
BigDecimal is also good in certain circumstances for controlling precision, but there are gotchas
BigDecimal is also good in certain circumstances for controlling precision, but there are gotchas
ASKER
Open in new window