Reputation: 25
I'm trying to let the user enter the length of a song except they can enter the length as 5.76 for example. Is there a way I can format that 6.16?
This is how they enter the duration if it makes any difference:
System.out.println("Please enter the length of the song");
double length = sc.nextDouble();
Upvotes: 0
Views: 3967
Reputation: 2833
The code below will split the entered time into minutes and seconds, and then operate on the seconds entry to calculate the total number of minutes and seconds are represented by that number.
EDIT Modified the code so that trailing zeroes are not truncated.
System.out.println("Please enter the length of the song");
String length = sc.next("\\d+\\.\\d{2,}");
String[] split = ("" + length).split("\\.");
double minutes = Double.parseDouble(split[0]);
double seconds = (Double.parseDouble(split[1]));
seconds = (Math.floor(seconds / 60)) + ((seconds % 60) / 100);
System.out.println(minutes + seconds);
Upvotes: 1
Reputation: 3239
With the following code, you can convert to minutes and seconds, then output that however you want, including put it back into a double (as shown).
int minutes = Math.floor(length);
length -= minutes;
length = Math.floor(length * 100.0);
if (length > 59) {
minutes++;
length -= 60;
}
int seconds = Math.floor(length);
length = ((double) minutes) + ((double) seconds) / 100.0;
Upvotes: 0
Reputation: 2004
Get the decimal value and check if its greater than 0.6. You can then subtract it from 0.6 and add that difference and 1 to the floor of the orignal number.
double dec = length - Math.floor(length);
if(dec > 0.6){
double diff = dec - 0.6;
length = length + 1 - dec + diff;
}
However, this might cause a lot of decimals due to the way double
is stored in Java. You could get around this, but you should really use a different value to store hours and minutes than a double. You could use an integer for each, and you could initially scan in the input as a String and then process it.
Upvotes: 0