将double格式化为分钟和秒

时间:2013-12-19 23:32:14

标签: java time formatting

我试图让用户输入歌曲的长度,但他们可以输入长度为5.76。有没有办法可以格式化6.16?

如果它们有任何不同,这就是他们进入持续时间的方式:

System.out.println("Please enter the length of the song");
double length = sc.nextDouble();

3 个答案:

答案 0 :(得分:0)

获取小数值并检查其是否大于0.6。然后,您可以从0.6中减去它,并将该差值和1添加到原始数字的最低点。

double dec = length  - Math.floor(length);
if(dec > 0.6){
    double diff = dec - 0.6;
    length = length + 1 - dec + diff;
}

但是,由于double存储在Java中的方式,这可能会导致大量小数。你可以解决这个问题,但你应该使用不同的值来存储小时和分钟而不是双倍。您可以为每个使用一个整数,并且最初可以将输入扫描为String,然后对其进行处理。

答案 1 :(得分:0)

下面的代码会将输入的时间分为几分钟和几秒,然后对秒条目进行操作,以计算总分钟数和秒数。

编辑修改了代码,以便不会截断尾随零。

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);

答案 2 :(得分:0)

使用以下代码,您可以转换为分钟和秒,然后根据需要输出,包括将其放回双精度(如图所示)。

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;