홍한석
홍한석

Reputation: 481

Elixir: float to formatted string

I do a simple code kata in codewars, solving followed problem:

Series: 1 + 1/4 + 1/7 + 1/10 + 1/13 + 1/16 +...

I've got an error about test like this:

series sum (6.0ms)
  1) test series sum (TestSeries)
     fixture:6
     Assertion with == failed
     code: sum(0) == "0.00"
     lhs:  '0.00'
     rhs:  "0.00"
     stacktrace:
       fixture:7 

Are they different in Elixir, '0.00' and "0.00"?

And formatting the float to string is hard work like this?:

# My Solution
defmodule Series do
  def sum(n) do
    n
    |> gen_series
    |> do_sum
    |> make_format
  end

  def gen_series(n) do
    if n == 0 do
      [0.00]
    else
      for x <- 1..n, do: 1/(1+3*(x-1))
    end
  end

  def do_sum(series) do
    series
    |> Enum.reduce(&(&1+&2))
  end

  def make_format(sum) do
    :io_lib.format("~.2f", [sum])
    |> Enum.at(0)
  end
end

Upvotes: 1

Views: 841

Answers (2)

Nathan Long
Nathan Long

Reputation: 126122

To round a float to a given precision and format it as a string (binary), you can use :erlang.float_to_binary/2.

:erlang.float_to_binary(987.3, [decimals: 2]) # => "987.30"
:erlang.float_to_binary(387.39947423, [decimals: 4]) => "387.3995"

This function can also give you a scientific or compact format. See h :erlang.float_to_binary/2 in iex.

Upvotes: 0

vahid abdi
vahid abdi

Reputation: 10318

Are they different in Elixir, '0.00' and "0.00"?

yes they are

single-quote literal are charlist which is list of code points.

to convert float to string use the following:

def make_format(sum) do
    :io_lib.format("~.2f", [sum])
    # use to_string instead of Enum.at(0) which returns charlist
    |> to_string()
end

Upvotes: 1

Related Questions