i am using following function to format the double value to x.xx , but after that the result value started to end up with exponential value ( i have already read the answers which are advising to use the DecimalFormat or to plain text () methods but every where the system is giving error to change the types ...return types i am lost a bit now
can some one please help me in following method tweaks so that the returning values can be displayed as normal number instead of 3.343E32
Please note that the following function FD is used many times in code so i want to change it here only so i dont have to apply the formatting each and every results / variable..
public double fd(double x) {
BigDecimal bd_tax = new BigDecimal(x);
BigDecimal formated = bd_tax.setScale(2, BigDecimal.ROUND_UP);
x = Double.valueOf(formated.doubleValue());
return x;
}
You say, "...to format the double value...", but there is no code in your example that formats anything. Your fd(x) function takes a double as its argument, and it returns a double. It doesn't do anything else.
If your numbers really are in the neighborhood of 3.343E32, Then they're going to have a lot of digits: 33 digits before the decimal point. Is that what you were expecting?
Suggest you look at String.format() if you are trying to turn the double value into human readable text. Something like this, perhaps:
public String fd(double x) {
return String.format("%.2f", x);
}
Related
I want to round off any double to a String with 2 decimal places in Java.
I have tried using DecimalFormat but it doesn't give the expected results.
Any help would be appreciated.
Ex: I/P: 3402100.5323
I want to convert this to:
O/P: 34.02
I've tried using DecimalFormat("##,##,##0.00", new DecimalFormatSymbols(Locale.US))
but this results in 34,02,100.53 whereas I want it to output 34.02
PS: If the I/P is 34.02 I would expect it to remain same even after applying the formatting
In my opinion, this can be achieved in 2 steps:
Transform the number into your customised
round-off. (3402100.5323 to 34.021005323). Divide the input with power of 10 to make it round to 2 digits.
Then transformed number can be pretty-printed to truncate value after 2 decimals (34.021005323 to 34.02)
public static void main(String[] args) {
double input = 3402100.5323;
double output = input / getDivisor(input);
System.out.printf("%.2f%n", output);
}
private static double getDivisor(double input) {
int length = String.valueOf((long) input).length();
return Math.pow(10, length - 2) ;
}
Output: 34.02
String.format("%0.2f", 34.021005323)
See
https://docs.oracle.com/javase/7/docs/api/java/lang/String.html#format(java.lang.String,%20java.lang.Object...) and
https://docs.oracle.com/javase/7/docs/api/java/util/Formatter.html#syntax
Turning one number into something completely different is, naturally, not the job of decimalformat.
To get from a number representing 3402100.5323 to the string "34.02", first you'd have to get a number that is closer to "34.02". In other words, divide by 10000.0 first.
From there, String.format("%.2f") seems like an easy path: That renders any double to a string, but never using more than 2 digits after the decimal separator. If you want 3400000.123 to turn into "34.00" and not "34", you can make that String.format("%.02f") to force the zeroes.
public String renderWhateverThatIs(double in) {
return String.format("%.02f", in / 100000.0);
}
renderWhateverThatIs(3402100.5323);
> 34,02
Note that the machine locale will dictate if you see a dot or a comma as separator. You can force the issue by explicitly passing a locale to format.
I think what you're looking for is the java.math.BigDecimal class (https://docs.oracle.com/javase/8/docs/api/java/math/BigDecimal.html).
In your case, it would look like this:
BigDecimal rounded = BigDecimal.valueOf(yourDoubleValueHere).setScale(2, BigDecimal.ROUND_HALF_UP);
System.out.println(rounded); // 34.02
It can replace doubles (with more complex syntax though) by basically storing numbers in their decimal form, which means you could make operations on it and keep having two decimal places and avoid rounding issues.
EDIT: after thinking about it, it's probably overkill since you only want to get a String with the rounded value, but I'll leave it there just in case.
I don’t believe you can achieve what you want (First 4 digits converted into a 2 digit double with 2 decimal places) in a single step. I’ll break down the steps for an approach that I would try:
Convert the input double to a string
double d = 3402100.5323;
String dStr1 = String.valueOf(d); // dStr1 will be “3402100.5323”
Next, remove the decimal from the string
String dStr2 = dStr1.replace(‘.’,’’); // dStr2 will be “34021005323”
Then, grab the first 4 digits you are interested in
String dStr3 = dStr2.substring(0,4); // dStr3 will be “3402”
Finally, insert a decimal point
String result = dStr3.substring(0,2) + “.” + dStr3.substring(2); // result will be “34.02”
You can use format for this try this out it work 100% for me.
String.format("%.2f", value)
Helpful link
https://docs.oracle.com/javase/7/docs/api/java/util/Formatter.html#syntax
I have a method which returns a double
public double getOdds() {
return odds;
}
This works completly fine. However, the problem is when the data is displayed, it automatically rounds the inserted value up. I want to prevant that, and get a value with 2 decimals.
Here are my JSP where I call the method. The ArrayList "bets" consist of all values entered by the user. But, as explained above, when the user enters 2.75 then it will return 3.0
ArrayList <bets> bets = betsDAO.getBets(x, y);
for (bets bet : bets) {
<td><%=bet.getOdds()%></td>
}
I'm still new to Java, and have tried looking for solutions, but unfortunatly I have not been able to solve the issue.
when the user enters 2.75 then it will return 3.0
The only reason for that to happen is if the value is limited to zero decimals at some point. Java only does that for int (or long or short or char or byte) values, and those are truncated, so result would be 2, not 3.0.
The only round-to-nearest I can envision is caused by the database or the JDBC driver:
The column type in the database is INTEGER or NUMBER(5,0) or something like that. Check your database schema.
The code reading the database (betsDAO) is calling getInt(...) and the JDBC driver rounds the value for you.
Anyway, the error is in code you haven't shown.
it depends on which data type you intend on working with, but this
should do the trick for you
public class Rounding {
public static void main(String[] args) {
//using string format
double input = 3.14159265359;
System.out.println("double : " + input);
System.out.println("double : " + String.format("%.2f", input));
//using Decimal format
double num = 1.34567;
DecimalFormat df = new DecimalFormat("#.###");
df.setRoundingMode(RoundingMode.CEILING);
System.out.println(df.format(num));
}
}
OUTPUT:
double : 3.14159265359
double : 3.14
double : 3.14
OUTPUT:
1.346
so you can be more specific here with the decimal point to return. it all depends on the importance of the decimal precision for your project
Couldn't Math.floor help with the rounding? it rounds down, and if you ever need to use rounding up then use Math.ceil.
hopefully this helps!
Is there any method to remove the . in java into a double value?
Example :
56.11124
to
5611124
I don't think there's a mathematical way to find out how many decimals there are in a double. You can convert to a String, replace the dot, and then convert it back:
Double.parseDouble(Double.toString(56.11124).replace(".", ""));
Be careful of overflows when you parse the result though!
Here's one way to do it,
First, convert the double to a string. Then, call replace to replace . with an empty string. After that, parse the result into an int:
double d = 5.1;
String doubleString = Double.toString(5.1);
String removedDot = doubleString.replace(".", "");
int result = Integer.parseInt(removedDot);
Obviously, this wouldn't work if the double's string representation is in scientific notation like 5e16. This also does not work on integral double values, like 5, as its string representation is 5.0.
doubles are inaccurate by nature. 5 and 5.0 are the same value. This is why you can't really do this kind of operation. Do you expect different results for a and b?
double a = 5;
double b = 5.0;
If you do, then you can't really do this, since there is no way of knowing what the programmer wrote exactly at runtime.
This might work
class Example {
public static void main(String[] args) {
double val = 56.1112;
while( (double)((int)val) != val )
{
val *= 10;
}
System.out.printf( "%.0f", val );
}
}
Output: 561112
This works by casting the double to int which truncates the floating information 56.11124 => 56. While the values aren't equal you multiply it by the base to push the . out. I don't know if this is the best way.
You can convert to BigDecimal and use the unscaledValue method:
BigInteger unscaled = new BigDecimal(myDouble).unscaledValue();
Depending on your intended output, you might also use BigDecimal#valueof(double) to create the intermediate BigDecimal.
Javadoc for BigDecimal#new(double)
Javadoc for BigDecimal#valueOf(double)
Javadoc for BigDecimal#unscaledValue()
You can convert it to a String and remove the . and convert it back to double something like
double value = 56.11124;
value = Double.valueOf(("" + value).replace(".", "")).doubleValue();
This will return 5611124.0 since its a double you will have the floating point. You can convert it to an int, but you have to take care of the possible overflow. Otherwise it would look like this
int normalized = (int) value;
In my program i'm posting the payment amount value to controller and i'm converting that value to Integer. Because I need to convert this value to cents before calling web service.
I'm using java and convert String to Integer code given below
(int)(Double.parseDouble(httpRequest.getParameter(PAYMENT_AMOUNT).trim()) * 100);
payment.jsp
page look like this
Payment Amount: <input type="text" id="paymentAmount" name="paymentAmount" value="1.00" />
For many input values it gives the correct output.
But for some values like 8.03 as input it return 802 as output value . This happens in 9.03,9.04 ,10.03,10.04,11.03 etc ... what could be the reason for this issue?
You need to round the result. The problem you have is that floating point numbers are almost but not exactly the number it appears when printed as a string. This shows up as a problem when you perform calculations.
I suggest you try
(int) Math.round( Double.parseDouble( httpRequest.getParameter(PAYMENT_AMOUNT).trim()) * 100);
In your specific case, you can see with BigDecimal what the actual representation of a double is
double d = 8.03;
BigDecimal bd = new BigDecimal(d);
System.out.println("bd: " + bd);
double d100 = d * 100;
System.out.println("d100: " + d100);
int i100 = (int) d100;
System.out.println("i100: " + i100);
int r100 = (int) Math.round(d100);
System.out.println("r100: " + r100);
prints
bd: 8.0299999999999993605115378159098327159881591796875
d100: 802.9999999999999
i100: 802
r100: 803
So you can see the actual value of 8.03 is slightly less than 8.03 which means however that when you * 100 and round down it means that you get 802 not 803 as expected.
The best solution is to round the result which finds the closest representable value.
As a side note, you might want to reconsider using int types to store cent values esp when dealing with large numbers.
To add more to earlier answers on floating-point issues in Java, and the need for BigDecimal, refer to some explanation here:
http://www.drdobbs.com/jvm/javas-floating-point-imprecision/240168744
You can change your code to:
(new BigDecimal(httpRequest.getParameter(PAYMENT_AMOUNT).trim(), MathContext.DECIMAL64)).multiply(new BigDecimal(100, MathContext.DECIMAL64)).intValue()
Another note: I would be cautious about assuming that you will get a String object back in the getParameter() call above esp. if someone is attempting to call your service without passing the PAYMENT_AMOUNT parameter.
For a project at school, I have to make a java program to retrieve data from a database.
This is my code:
import java.text.*;
import java.util.*;
public class Tijdstip
{
public Tijdstip()
{
}
public double testTijd(String tijdstip1)
{
// splitting the time
String[] tokens = tijdstip1.split("\\s+");
int hours = Integer.parseInt(tokens[0]);
int minutes = Integer.parseInt(tokens[1]);
//returning the time
double result = hours + ((double)minutes/100);
return result;
}
}
I fill in a time as string like: "7 10", meaning 7:10am and it must return a double like 7.10
But it returns 7.1, how do I make it so it will return 7.10 instead of 7.1?
You need to understand the difference between how a number is represented and how it is displayed. There is no numeric difference between 7.1 and 7.10; there is no way to make the number one instead of the other. You can display 7.1 as 7.10 using output formatting such as found in the Format class.
As a side issue: Storing this as a double would be a bad idea in a program of any size. There are many classes for representing time, and they all take into account the non-decimal nature of time divisions. Doubles don't do this.
Try this
new DecimalFormat("#.00").format(result);
The short answer is that you cannot do this if you must keep the result as a double. The double doesn't know anything about leading or trailing zeros. You can only do this when the result is formatted as a String. E.g., String.format("%.2f", 7.1) gives the string "7.10". You can easily do this formatting every time you display the number, but you cannot make the number itself remember the extra zero.
When you return double it will always truncate your last number if it is zero. so make it a string and return
If you need double value which has only two digits after dicimal, you can try following:
double d = 1.164444;
double r = Math.rint(d * 100)/100;
System.out.println(r);