Convert a string to double with precision
I am getting a value amount of say $45.00 from a jsp and set this value as a string for my other work. then i am changing this string to double by using this statement
setAmount(Double.parseDouble(cstmt.getString(1)));
my precision is lost when i get this amount it just shows 45.0 how can I get the precision of 45.00
I would appreciate if any assistance is provided for the problem.
thanks
JSP's can use NumberFormat.
However you should never use float/double to represent monetary values. Money has an absolute value (in terms of units used to purchase). Float and double do not (actually they do but they are in base 2 NOT base 10 like most money is). In most cases representation errors due to float and double do not really matter (if you have suitably analysed the usage of them) however people get very upset about errors when it comes to money
matfud.
Similar Messages
-
Convert String to double with two digits
How can I format "String" type of numbers (eg. 199.0, or 199) to return a "double" type of nubmers like 199.00, or 199.00. It should have two digits.
For example, the input is String of 199.0, how can I get "double" 199.00. Always format as two digits.
Thanks for your help,Thanks for replying.
Here is my code. For some reason, when convert the returned String back to double in main, it cut the "0".
What's wrong with my code? How can I get that 4.60 in double type.
Thanks again,
==================================================================================
import java.text.*;
import java.util.*;
import java.sql.*;
public class NumUtils
// Convert Double to 99.99
public static String format(String str)
//double d = 4.6;
double d = Double.parseDouble(str);
NumberFormat formatter = new DecimalFormat("0.00");
formatter.setMaximumFractionDigits(2);
String s = formatter.format(d);
return s;
public static void main(String[] args)
String myDouble = "4.6";
String mynewdouble = format(myDouble);
System.out.println(" --- formatDouble = " + mynewdouble);
double my_d = Double.parseDouble(mynewdouble);
System.out.println(" --- Double = " + my_d); -
Problem in converting the String to Date with time zone GMT
Hi,
When I tried to convert the string 12/05/2009 to Date, the time zone is set to BST.On the other hand, for the date 12/12/2009, the time zone is set to GMT. What should I do to get the time zone as GMT all the time.?
SimpleDateFormat formatter = new SimpleDateFormat("dd/MM/yyyy");
String dateString = "12/05/2009";
System.out.println(myDate.toString());I think you are all missing the point. java.util.Date objects always alway always store the date as the number of milliseconds since 1/1/1970 UTC so the only TimeZone they have its the implicit UTC. When you use the Date.toString() method the toString() method gets the default time zone from your environment and formats the data accordingly. This means that the same Date object will, by default, produce a different result for France and Australia and the US.
So, if you have the date "12/5/2009" as a String then to convert it to a java.util.Date you must specify what TimeZone is implied. If it is your system time zone then you can just create a SimpleDateFormat object with the correct format and then use the parse() method to create the java.util.Date object and this will automatically be converted to UTC. If the date String represents some other time zone then you must explicitly set the time zone of the SimpleDateFormat object before parsing the string.
The same approach applies when converting a java.util.Date object to a String. If you want anything other than your system time zone then you must explicitly tell the SimpleDateFormat what time zone you want the result formatted for. -
Converting from string to double (formula)
Hi All,
I have a formula stored in properties file (i am doing some android dev) and retrieveing that formula using following stmt
double c = 35.0;
String res = this.getResources().getText(R.string.celsiusfahrenheit).toString();
The returned value of string res is (1.8*c)+32
How do i make the above stmt to substitue value of c into above equation and returned me the result value.
thx
vinodvinod_kmr wrote:
Hi All,
I have a formula stored in properties file (i am doing some android dev) and retrieveing that formula using following stmt
double c = 35.0;
String res = this.getResources().getText(R.string.celsiusfahrenheit).toString();
The returned value of string res is (1.8*c)+32
How do i make the above stmt to substitue value of c into above equation and returned me the result value.
thx
vinodas I understand you actually want to solve. if so, and res always returns that formula, then you can skip the properties file and just solve it already. something like:
double result = (1.8*c) + 32.0if the result you are looking for is res with the value of the double substituted for c in the formula then the first step is to convert the the double c into a string and sticking that in res using String.replace(). something like
res = res.replace("c", Double.toString(c));of course I don't know if String in android is like java.lang.String (same with Double) but I'm sure an equivalent exist. -
How to convert a string into double?
Hi. I'm having a string with 10340.8878 which is essentially a GPS latitude coordinate. I will need to break it up separately into double type 103,40 and 88.
103 refers to the degree
40 refers to the minutes
88 refers to the seconds
I will also need to perform a double conversion: the second separated double(40) divided by a factor of 60 and the third separated double(88) divided by a factor of 360.
How can i go about doing this?
Thanks!new Double(str).doubleValue();
http://java.sun.com/j2se/1.4.1/docs/api/java/lang/Double.html -
How do I convert a String to double~?
The contents of a file named data.txt are shown below:
1.2402 .7930 .3254 -.0994 -.2930 -.4233 -.4539 -.1423
-.0007 -.3118 -.6208 -.9524 -1.3694 -1.3870 -.9214 -.3621
.1633 .9746 2.0815 2.5352 1.8879 1.0037 .3276 -.2085
I want to read these data from data.txt.
Below are the code I use to read file:
//read file
BufferedReader br = new BufferedReader(objFileReader);
//lstrLine contains one line data,
String strLine = br.readLine();
Question:How can I convert String strLine to double [ ] dbLine ?
For example,convert String strLine=" 1.2402 .7930 .3254 -.0994 -.2930 -.4233 -.4539 -.1423" to dbLine[0]=1.2402,dbLine[1]=.7930,dbLine[2]=.3254,dbLine[3]=-.0994,dbLine[4]=-.2930,dbLine[5]=-.4233,dbLine[6]=-.4539,dbLine[7]=-.1423String.split(), DecimalFormat
-
Strange outputs while parsing String to Double
Hi All,
I am writing a simple MIDlet on MIDP 2.0 and CLDC 1.1, where I need to convert two strings into Double calculate their difference and then display the result back on the screen.
The code I am using is:
double difference = Double.parseDouble("1235.7") - Double.parseDouble("1234.5");
String result = (String)Double.toString(difference); The output generated is : 1.2000000000000455 which should be only 1.2
If I replace the values with "1235" and "1234.1" the output is 0.900000000000091 which should be 0.9
However, if I change the values to "1235.6" and "1234.1" the output generated is 1.5 which is perfectly fine. Means this happens only for some specific set of values.
Has anyone ever faced such a situation or if anyone knows a proper workaround to fix this please help me out.
Thanks.Is this normal? does this also happens in case of J2SE I have never tried a similar
program on j2se.If you are talking about the innaccuracies in the calculations then yes. Look at the url I gave in my previous post, some guy was asking the same thing and it wasn't about J2ME.
In fact, this happens in every other language as well. It a limitation of the format doubles are stored in.
shmoove -
In look out for code to blindly converting a string to boolean
I have an expression (String) which is a boolean by syntax, already has embeded && , ||, ! and |, & operators. So, I would like to convert my String in boolean with least effort..I do not intend to use other math operators.
Any suggestions?See the replies of your previous post.
-
How do I convert a string to a double, a number loses the precision
I tried converting a string to a double but that limits the precision. I need to convert a string to a double.
If you use the Scan From String function, the default is to convert to a dbl. If you're looking at a front panel indicator, don't confuse the format and precision of the indicator with the type representation. You can set the indicator to display as many digits as you want but that doesn't change the actal number stored in memory.
-
Converting a String to a Double, may I use Double constructor?
Hello,
I need to convert A String to a Double in my application.
Usually I use the Double.parseDouble(String) method that works fine.
But I have found one line in the code that use the Double class constructor: new Double(String). It has been observed that that constructor sometimes throws NullPointerException.
My question is, are theses two methods both good practices to do the convertion? Could threre be a multi-threading problem with the Double construtor?
I'm using JDK 1.3.1.
Here is a sample of stack trace:
bvsmgr: java.lang.NullPointerException
at java.lang.FloatingDecimal.readJavaFormatString(Unknown Source)
at java.lang.Double.valueOf(Unknown Source)
at java.lang.Double.<init>(Unknown Source)
Thank you for all answers,
Florent.But I have found one line in the code that use the
Double class constructor: new Double(String).
It has been observed that that constructor sometimes
throws NullPointerException.
My question is, are theses two methods both good
practices to do the convertion? Could threre be a
multi-threading problem with the Double construtor?Both methods are the same (they both use valueOf()), and if the c'tor throws an NPE, then only because you feed it null. parseDouble would do that, too. -
Having trouble converting a string to a double
Im having problems converting a string to a double in my jsp pages, i have pasted part of the code that is causing the problem. Just a note, i have imported the java.lang.* classes also
while ( rs.next() )
String price = rs.getString("price");
sPrice = double.parseDouble(price);
out.println("<TD>$" + decimalFormat.format(sPrice) + " </TD>");
An error occurred at line: 140 in the jsp file: /cs399/AddToShoppingCart.jsp
Generated servlet error:
[javac] Compiling 1 source file
C:\jakarta-tomcat-4.1.29\work\Standalone\localhost\_\cs399\AddToShoppingCart_jsp.java:277: class expected
sPrice = double.parseDouble("price");
^double is a primitive. You want java.lang.Double, with a capital "D":
sPrice = Double.parseDouble(price);MOD -
CRADSDatabase ERROR (5211): There is an error converting Unicode string to or from code page string
Device Blackberry Z10
Sw release 10.2.1.2977
OS Version 10.2.1.3247
The problem is known by Blackberry but they didn't make a little effort to solve this problem and they wonder why nobody buy Blackberry. I come from Android platform and I regret buying Blackberry: call problems(I sent it to service because the people that I was talking with couldn't hear me), jack problems (the headphones does not work; I will send it again to service). This synchronisation problem is "the drop that fills the glass". Please don't buy Blackberry any more.
http://btsc.webapps.blackberry.com/btsc/viewdocument.do?noCount=true&externalId=KB33098&sliceId=2&di...This is a Windows registry issue, if you search the Web using these keywords:
"how to fix craddatabase error 5211" you will find a registry editor that syas it can fix this issue. -
StringTokenizer class problem with strings in double quotes
Hello Technocrats,
I have a problem with tokenizing following string enclosed in (). (abc," India, Asia", computer engineer). My separator is ",", thus StringTokenizer class gives me 4 tokens namely abc, "India, Asia" and computer engineer. But I require that String in double quotes should be a single token. How to achieve this using StringTokenizer class? Or is there any other way?
Thanks in advance.Try
String[] str="abc,\" India, Asia\",computer engineer".split(",",1);
for(String s: str)
System.out.println(s);
}Thanks. -
How to convert a string to a currency value ? getting a dump with exception
Hi,
I am getting a exception not caught in CX_SY_CONVERSION_NO_NUMBER.
I am trying to convert a string value with ',' to a currency value.
I tried using Replace and Condense. But the error still persists.
Is there a FM or a casting that I can use?
Cheers
KiranHi,
Sorry I got my question wrong. I have a problem - that when I'm trying to pass a value from a string to a currency field.
But, the currency field is a field symbol.
so, I have
data abc type string.
abc = "5345"
<curr_val> = abc.
now <curr_val> = 0.000
Please suggest. -
Need to know the best practice for converting string to double
I have a string and want to convert to double if it is a valid number, else want to keep as it is. There can be couple of ways doing it and I want to know which one is best if I have lots of strings, specially from performance point of view.
1) Use Double.parseDouble(myString) and catching Number format exception to detect it is not a number. One of my colleague said it does not give good performance because of exception catching,
2) Use of org.apache.commons.lang.math.NumberUtils.isNumber() and if it is true then only parse it - so don't rely on exception.
I did some performance testing - putting it in a loop and trying out for 2 scenarios - one loop for proper numeric value string and another for non-numeric. What I found out was if strings are not proper then parseDouble() is taking long time (because of exception catching) and in that case using NumberUtils.isNumber() makes sense.
Would like to hear expert views on this.
Thanks
ManishaIf you need it as a double you must convert it to a double and catch the exception. This means that testing it first is a waste of time in the case when the test succeeds - did your colleague think of that?
Catching the exception is possibly slower than the test. Whether this is significant depends on the relative timings of the test and catching the exception, and also on the expected error rate. If this is below about 40% I suggest your colleague is talking through his esteemed hat.
And of course the best test by far is the conversion itself. Using any other test runs the risk of its rules being different from those applied by the conversion.
In any case you are obliged to write the code that catches the exception. You're not obliged to write the pre-test code.
My personal rule for efficiency is to minimize lines of code until hard evidence to the contrary proves that further improvement is required.
Maybe you are looking for
-
Iphone 5 is going crazy please help
for some reason my iphone is having a paddy, it has 51 picutures on but it has used 6GB??? help please
-
Warehouse Mgmt :: Urgent
Dear All, I am implementing WH. My query is that lets say i have a material Material : 1998 I have recieved the material in a Storage Bin (01-01-01). System saves the GR date. & If someone wants to use FIFO stock removal strategy then the system uses
-
can i get Apple to change the credit card billing procedures ( ie have them re-bill me for one total amount rather than them currently to have billed me on a piecemeal items basis?
-
Configuring J2EE Appl to obtain security roles from authentication Subject
http://www.oracle.com/technology/products/jdev/howtos/10g/jaassec/index.htm says "Oracle JDeveloper can be used to add the orion-application.xml file to a web project, choosing orion-application.xml from the list of Deployment Descriptors in the JDev
-
Oracle migration from solaris to AIX
Hi, We have a activity of a migration of oracle 9i Solaris database (800G in size) to AIX oracle 10g database, we use RMAN and exp/imp as a backup method. What are the efficient and fastest methods to do this and i what way? Thanks Jaffy