是否有更好的方法将秒格式化为mm:Elix中的ss格式?

时间:2016-10-12 15:01:11

标签: elixir

我目前正在使用以下代码将秒格式化为mm:ss格式。有更好的选择吗?

   def formatted_length(length) do
     minutes =
      length/60
      |> Float.floor()
      |> round()
      |> Integer.to_string()

     seconds =
      rem(length, 60)
      |> Integer.to_string()
      |> String.rjust(2, ?0)

     minutes <> ":" <> seconds
   end

1 个答案:

答案 0 :(得分:4)

您的代码实际上是错误的:对于90,它会返回"2:30"

您可以使用div进行整数除法,忽略小数部分。至于其余部分,我会使用字符串插值来缩短代码:

defmodule Main do
  def formatted_length(length) do
    "#{div(length, 60)}:#{formatted_seconds(rem(length, 60))}"
  end

  defp formatted_seconds(s) when s < 10, do: "0#{s}"
  defp formatted_seconds(s), do: "#{s}"
end

13 |> Main.formatted_length |> IO.puts
123 |> Main.formatted_length |> IO.puts
143 |> Main.formatted_length |> IO.puts

输出:

0:13
2:03
2:23