2

TimeUnit.toSeconds works well when the result is > 1. However, because we're dealing with longs, if the result is between 0 and 1 exclusive, we get 0 instead. Is the a java SDK function that handles double conversions for us?

I understand that I can perform these conversion myself by multiplying or dividing by the appropriate double. However, it is error prone and does not read well. My preference is to use an existing function from the Java SDK, similar to Java's TimeUnit.

Minimal example demonstrating my situation:

import java.util.*;
import java.util.concurrent.*;
public class Main {
    public static void main(String[] args) {
        System.out.println(TimeUnit.MILLISECONDS.toSeconds(1));
    }
}

Output:

0

I want a function that handles doubles that returns 0.001

4

2 回答 2

6

korolar 的建议非常好,值得作为答案并具有适当的格式。它给你大约一半的你想要的。如果您要自己进行乘法或除法,则至少可以从库枚举中取乘或除以的数字。

public static double millisToSeconds(long millis) {
    return (double) millis / TimeUnit.SECONDS.toMillis(1);
}

现在millisToSeconds(1)给出 0.001。我同意 JB Nizet 和 VGR 的评论,即您应该将计算包装在一个具有好名称的方法中,以使您的代码具有良好的可读性。如果您希望该方法更通用:

public static double convertTimeUnit(double amount, TimeUnit from, TimeUnit to) {
    // is from or to the larger unit?
    if (from.ordinal() < to.ordinal()) { // from is smaller
        return amount / from.convert(1, to);
    } else {
        return amount * to.convert(1, from);
    }
}

现在convertTimeUnit(1, TimeUnit.MILLISECONDS, TimeUnit.SECONDS)像以前一样给出 0.001,而convertTimeUnit(1, TimeUnit.SECONDS, TimeUnit.MILLISECONDS)给出 1000.0。

于 2018-03-14T12:20:14.483 回答
0

出色的!from我会通过添加额外的检查来增加该方法,以避免在两个和to参数中都传递相同的 TimeUnit 时发生无用的转换:

public static double convertTimeUnit(double amount, TimeUnit from, TimeUnit to) {
    // if the same unit is passed, avoid the conversion
    if (from == to) {
        return amount;
    }
    // is from or to the larger unit?
    if (from.ordinal() < to.ordinal()) { // from is smaller
        return amount / from.convert(1, to);
    } else {
        return amount * to.convert(1, from);
    }
}
于 2020-01-15T16:33:32.233 回答