Java - 仅打印小数部分的格式号**不带小数**

时间:2015-01-09 00:05:49

标签: java

之前曾问过这个问题(Formatting Decimal Number)而没有回答如何做到这一点而不显示小数。我一直在寻找答案无济于事。提前谢谢!

示例:

    System.out.println("It would take " + oneMileMins + " minutes and " + oneMileDfSecs.format(oneMileSecs) + " seconds for the person to run one mile.");

哪些输出: 这个人跑了一英里需要x分钟和.yy秒。

我希望.yy只是yy

2 个答案:

答案 0 :(得分:1)

只需将输出更改为oneMileDfSecs.format(oneMileSecs).replace(".", "")

即可

编辑:Rodney说" He did not ask for the proper equation he only asked how to remove the decimal.",所以我罢了以下内容,尊重他。

附加说明

就像 @Alan 所说,oneMileSecs应该等于(int)((oneMile % 1)*60),在这种情况下,你摆脱小数点的方式有点不同的

1)。如果您声明:

double oneMileSecs = (int)((oneMile % 1)*60)

然后将输出更改为:

String.valueOf(oneMileSecs).substring(0,String.valueOf(oneMileSecs).indexOf("."))

2)。如果您声明:

int oneMileSecs = (int)((oneMile % 1)*60)

然后直接输出oneMileSecs,因为它是int,它不会产生小数点

答案 1 :(得分:0)

不确定这是你正在寻找的答案,因为它没有回答标题中的问题(Fev的答案就是这样),但我认为这应该给出具体例子的正确结果:

private static void calcOneMile(double mph)
{
    double oneMile =  60 / mph;
    int oneMileMins = (int)oneMile;
    double oneMileFraction = oneMile % 1;
    int oneMileSecs = (int)(oneMileFraction * 60);
    System.out.println("It would take " + oneMileMins + " minutes and " + oneMileSecs + " seconds for the person to run one mile.");
}

或简化为:

private static void calcOneMile(double mph)
{
    int secondsToRunMile = (int)(1.0 / (mph / 3600));
    System.out.println("It would take " + (secondsToRunMile / 60) + " minutes and " + (secondsToRunMile % 60) + " seconds for the person to run one mile.");
}