Converting string like "15:45" into a double like 15.45 - java

I'm struggling to figure out how to convert a string like "15:45" into a double like 15.45,
I have previously come across methods like .toString() and was looking up a similar method to use in order to convert string to double, however there are several issues, I need to figure out how to make : be a place where dot . is inserted in double.
This is where I would like to use it.
if(westOne > (takeOff.firstInQueue().time)) {}
At the moment westOne is a double where as takeOff.firstInQueue().time is a string like "16.15" I'm assuming I'll need to create my own method to get this working so I can than apply it at the end of it?

You can simply:
myDouble = Double.parseDouble(myStr.replace(":", "."));
If that's really what you want, this will replace : with . and the String x:y will be the double x.y.
Edit:
If you want to add 5 minutes to the time, you can add 0.05 to the double and convert it back to String, but this is not a good way of doing it because:
You should take care of cases like 14:55, adding 0.05 will result 14.6.
And cases like 14:45 where adding 0.05 will result 14.5 (No 0 after 5).
If all what you want is to add 5 minutes to the time, you can use SimpleDateFormat and Calendar:
String myStr = "17:23";
SimpleDateFormat dateFormat = new SimpleDateFormat("HH:mm");
Date date = df.parse(myStr );
Calendar calendar = Calendar.getInstance();
calendar.setTime(date);
calendar.add(Calendar.MINUTE, 5);
myStr = dateFormat.format(calendar.getTime()); //Now myStr will be 17:28

I think this would work;
String value;
double value1;
value = String.replaceAll(":",".") // Converts the 15:45 to 15.45
value1 = Double.parseDouble(value) // Converts the 15.45 to a double value.

String timevalue = "15:45";
Double pointvalue = Double.parseDouble(timevalue.replace(':', '.'));
//Not double quote like the previous answer because it takes a char as a parameter and not a string

Related

Returning a double value but with a trailing zero at the end

Double d = 10.30
When I use this value of d i.e 10.30 it becomes 10.3
Is there anyway that I can sustain this value of 10.30
Remember I cannot change the data-type it should be a double
Is there a way??
You can't do this with Double class.
If you want to display a value with zero you could do this:
System.out.printf("%.2f%n", d);
It means that your variable d will be displayed with 2 digits after point. So, if d = 10.3, the code above will show 10.30
String also can store formatted value:
String s = String.format("%.2f%n", d);
System.out.println(s);
A double only contains only information about the value it represents, but not about the precision of it.
Whether a double is represented as 10.3, 10.30, 10.300000 etc. is determined by the display resp. string conversion routine, not by the routine which generates the value.
The best solution is
private static final DecimalFormat df = new DecimalFormat("0.00");
df.format(amountDouble)

How to convert the 6020494385.89982 string value to double

How to convert the "6020494385.89982" string value to a double?
String ss = "6020494385.89982";
double dd = Double.parseDouble(String.valueOf(ss));
System.out.println(dd);
I am getting the output as
6.02049438589982E9 but I want 6020494385.89982 as double value.
Use of a DecimalFormatobject should do the trick
String ss = "6020494385.89982";
double dd = Double.parseDouble(String.valueOf(ss));
System.out.println(new DecimalFormat("#0.00000").format(dd));
Or you can use System.out#printf()
System.out.printf("%.5f", dd);
Because System.out.println has a particular way of working with double precisions that will not work in this particular case for example.
The number is correct. 6.02049438589982E9 is just the scientific notation, which is the default when you print a double. If you want the non-scientific notation, you could just use printf instead of println:
System.out.printf("%f\n", dd);
6.02049438589982E9 is the same as 6020494385.89982
6.02049438589982E9 = 6.02049438589982 X 10^9
the value stored in the double is 6020494385.89982 However, when you print it out, it represents in this format: 6.02049438589982E9
You do not need to convert into double if in the end you want the representation in the same format as the current value of ss variable.
However if you need to convert for some other purpose and then need to show in that format later/else where you can use DecimalFormat as others have suggested.

Compare string within numerical ranges - Java

I need help with this string format: "08/13/2015 10:03:50"
I would like to compare the time within a range of 2 min. I get regex to a point but would not know how to go about this when the time is in string format and the cross over to another hour, (Ex. 10:59:30 would lap over to 11:01:30 not 10:61:30).
Code would be something like
string1 = "08/13/2015 10:03:50";
string2 = "08/13/2015 10:05:50, 08/13/2015 10:55:50, 08/13/2015 10:15:50,
08/13/2015 10:14:50, 08/13/2015 10:25:50, 08/13/2015 10:55:50";
if(string2.contains("string1(with plus or minus 2 of string1 min)"){
//Pass
}
Code I am using to grab the date
DateFormat dateFormat = new SimpleDateFormat("MM/dd/yyyy HH:mm:ss");
Calendar cal = Calendar.getInstance();
String timeOfUpdate = dateFormat.format(cal.getTime());
System.out.println(timeOfUpdate);
Parse the Strings as Date like suggested in the comments, then retrieve the timestamps of both Date objects through the getTime() method. Subtract these two numbers from one another. This get's you the chronological distance of these times in milliseconds, which you can compare to your criteria converted to milliseconds.
Update regarding the date list addendum: To evaluate a String containing a list of dates, you have to split the string along the list separator into an array of strings by using String#split().
Then, you can parse each sub string into a Date object and retrieve the timestamp of each as per the #getTime() method mentioned in the first paragraph. Collect these timestamps into a list.
This list can be searched for entries within the expected range, for example using the Stream API's filter function (Java 8 and newer). Here's a short tutorial about that function.
Try executing the below steps:
Convert String1 into Date Object and apply getTime() method, store the result in some variable
Convert String2 into a array of Strings by using split on comma
Run a loop on results retrieved in step#2, inside loop
Convert each value fetched into Date Object
Call getTime on date object converted
Subtract this number with the one fetched in Step#1
Now you will get the difference in milliseconds(1 min = 60000 miliseconds)
if the difference is either greater than -120000 or less than 120000 miliseconds than break the loop and set the flag to true.
Let me know if you still face any issue.
You can use date.getTime() for getting date in milliseconds since 1970 and split your date string arrays :
int offsetMinutes = 2;
String string1 = "08/13/2015 10:03:50, 08/14/2015 10:05:50, 08/14/2015 10:05:50";
String string2 = "08/13/2015 10:05:49, 08/14/2015 10:05:50, 08/15/2015 10:05:50";
String[] string1Array = string1.split(",");
String[] string2Array = string2.split(",");
DateFormat format = new SimpleDateFormat("MM/dd/yyyy hh:mm:ss", Locale.ENGLISH);
for (int j = 0 ; j< string1Array.length;j++)
{
Date date1 = format.parse(string1Array[j].trim());
for (int i = 0; i < string2Array.length; i++) {
Date date2 = format.parse(string2Array[i].trim());
if (date1.getTime() >= (date2.getTime() + offsetMinutes * 60 * 1000) || date1.getTime() <= (date2.getTime() - offsetMinutes * 60 * 1000)) {
//Here we are
}
}
}

Java double to string with specific precision

I would like to convert double into String. I want it to have as few digits as possible and maximally 6.
So I found String.format("%.6f", d) which converts my 100.0 into 100.000000.
Max precision works correctly, but I would like it to be converted to 100 (minimum precision).
Have you got any idea what method is working like that?
Use DecimalFormat: new DecimalFormat("#.0#####").format(d).
This will produce numbers with 1 to 6 decimal digits.
Since DecimalFormat will use the symbols of the default locale, you might want to provide which symbols to use:
//Format using english symbols, e.g. 100.0 instead of 100,0
new DecimalFormat("#.0#####", DecimalFormatSymbols.getInstance( Locale.ENGLISH )).format(d)
In order to format 100.0 to 100, use the format string #.######.
Note that DecimalFormat will round by default, e.g. if you pass in 0.9999999 you'll get the output 1. If you want to get 0.999999 instead, provide a different rounding mode:
DecimalFormat formatter = new DecimalFormat("#.######", DecimalFormatSymbols.getInstance( Locale.ENGLISH ));
formatter.setRoundingMode( RoundingMode.DOWN );
String s = formatter.format(d);
This is a cheap hack that works (and does not introduce any rounding issues):
String string = String.format("%.6f", d).replaceAll("(\\.\\d+?)0*$", "$1");
String.format("%.0", d) will give you no decimal places
-or-
String.format("%d", (int)Math.round(f))
Couldn't you just make a setPrecision function, sort of like this
private static String setPrecision(double amt, int precision){
return String.format("%." + precision + "f", amt);
}
then of course to call it
setPrecision(variable, 2); //
Obviously you can tweek it up for rounding or whatever it is you need to do.

Move decimal point in double

I have this code:
Long dval = new Long((new Date()).getTime());
System.out.println("ogval:"+dval);
Double dd = (double)dval;
System.out.println("dval:"+dd);
Here is the output:
ogval:1381490769636
dval:1.381490769636E12
When I convert the value to Double, it adds a decimal point. Can I do the typecasting and get the value in double as it is?
The desired output would be:
ogval:1381490769636
dval:1381490769636
I have a function whose argument accepts only double value. When I try to pass a timestamp, it passes the decimal value inside the method.
I can't edit the function because its an inbuilt function of some package.
Simple answer is no.
Floating types can contain integer up to some arbitrary value, given by the way floats are stored. If the number is too big, it gets converted to decimal.
If you need to work with big integer values use BigInteger class.
Great tool to examine those imperfections is this float converter.
Try 123456789 in the float converter, it won't be stored exactly.
Use DecimalFormat, like:
Long dval = new Long((new Date()).getTime());
System.out.println("ogval:" + dval);
Double dd = (double) dval;
DecimalFormat format=new DecimalFormat("##########");
System.out.println("dval:" + format.format(dd));
Your problem is not with the type that you are using, but with the format that you are applying to it. Currently, the default format is used, because string + double implicitly calls Double.toString, which converts your specific double to a String using scientific notation. You can force a different format if you wish by using printf or any other formatting method that Java makes available to you:
System.out.printf("dval: %12.0f", dd);
(demo)
as an alternative you can try using bigdecimal
Long dval = new Long((new Date()).getTime());
System.out.println("ogval:"+dval);
Double dd = (double)dval;
System.out.println("dval:"+dd);
BigDecimal bd = new BigDecimal(dval);
System.out.println("bdval:"+bd.toPlainString());

Categories

Resources