현재 아래 코드를 사용하여 초를 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
귀하의 코드는 실제로 올바르지 않습니다.에 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
이 기사는 인터넷에서 수집됩니다. 재 인쇄 할 때 출처를 알려주십시오.
침해가 발생한 경우 연락 주시기 바랍니다[email protected] 삭제
몇 마디 만하겠습니다