What is the best way to separate double into two parts “integer & fraction” in java

前端 未结 5 970
礼貌的吻别
礼貌的吻别 2021-02-14 00:28

I have tried to separate 5.6 (for example) by the following method:

private static double[] method(double d)
{
    int integerPart = 0;
    double fractionPart =         


        
5条回答
  •  暗喜
    暗喜 (楼主)
    2021-02-14 00:33

    poor-man solution (using String)

        static double[] sp(double d) {
            String str = String.format(Locale.US, "%f", d);
            int i = str.indexOf('.');
            return new double[] {
                Double.parseDouble(str.substring(0, i)),
                Double.parseDouble(str.substring(i))
            };
        }
    

    (Locale so we really get a decimal point)

提交回复
热议问题