2017-08-10 63 views
0

我得到這個錯誤試圖解析字符串爲float:藥劑 - 解析字符串浮動導致錯誤

case insert_product_shop(conn, existing_product.id, existing_shop.id, String.to_float(posted_product["price"])) do 

錯誤:

20:45:29.766 [error] #PID<0.342.0> running Api.Router terminated 
Server: 172.20.10.2:4000 (http) 
Request: POST /products 
** (exit) an exception was raised: 
    ** (ArgumentError) argument error 
     :erlang.binary_to_float(58.25) 
     (api) lib/api/router.ex:120: anonymous fn/1 in Api.Router.do_match/4 
     (api) lib/api/router.ex:1: Api.Router.plug_builder_call/2 
     (api) lib/plug/debugger.ex:123: Api.Router.call/2 
     (plug) lib/plug/adapters/cowboy/handler.ex:15: Plug.Adapters.Cowboy.Handler.upgrade/4 
     (cowboy) /Users/Ben/Development/Projects/vepo/api/deps/cowboy/src/cowboy_protocol.erl:442: :cowboy_protocol.exe 
cute/4 

當我改變

case insert_product_shop(conn, existing_product.id, existing_shop.id, Float.parse(posted_product["price"])) do 
: 

我收到:

20:54:12.769 [error] #PID<0.336.0> running Api.Router terminated 
Server: 172.20.10.2:4000 (http) 
Request: POST /products 
** (exit) an exception was raised: 
    ** (ArgumentError) argument error 
     :erlang.binary_to_float(24) 
     (api) lib/api/router.ex:82: anonymous fn/1 in Api.Router.do_match/4 
     (api) lib/api/router.ex:1: Api.Router.plug_builder_call/2 
     (api) lib/plug/debugger.ex:123: Api.Router.call/2 
     (plug) lib/plug/adapters/cowboy/handler.ex:15: Plug.Adapters.Cowboy.Handler.upgrade/4 
     (cowboy) /Users/Ben/Development/Projects/vepo/api/deps/cowboy/src/cowboy_protocol.erl:442: :cowboy_protocol.exe 
cute/4 

如何正確解析字符串以便浮動?我也可以允許它是一個字符串或浮動,如果它是字符串,解析爲浮動?

+3

根據錯誤消息,您已經有一個浮點數。只需使用'posting_product [「price」]''。 – Dogbert

回答

3

根據錯誤,它看起來像輸入已經是Float

** (ArgumentError) argument error 
    :erlang.binary_to_float(58.25) 

事實上,String.to_float/1如果輸入不是String引發錯誤。

iex(1)> String.to_float(58.25) 
** (ArgumentError) argument error 
    :erlang.binary_to_float(58.25) 
iex(1)> String.to_float("58.25") 
58.25 

還要注意的是String.to_float/1也抱怨,如果輸入沒有小數位數。

iex(2)> String.to_float("58") 
** (ArgumentError) argument error 
    :erlang.binary_to_float("58") 
iex(2)> String.to_float("58.0") 
58.0 

您需要編寫自定義函數。我不確定posted_product["price"]是從哪裏來的,而且您是否期望它有不同的輸入類型。這可能是一個錯誤。

一個可能的解決方法是將輸入總是轉換爲String,並使用Float.parse/1

iex(12)> {f, _} = Float.parse(to_string("58.0")) 
{58.0, ""} 
iex(13)> f 
58.0 
iex(14)> {f, _} = Float.parse(to_string(58.0)) 
{58.0, ""} 
iex(15)> f 
58.0 

注意Float.parse/1可能會返回一個:error,因此你必須處理。

另一個選擇,也許稍微有效一些,只有在必要時才使用is_float/1is_string/1來處理轉換。

defmodule Price do 
    def to_float(input) when is_float(input) do 
    input 
    end 
    def to_float(input) do 
    case Float.parse(to_string(input)) do 
     {f, ""} -> f 
     _  -> :error 
    end 
    end 
end 

iex(2)> Price.to_float(32) 
32.0 
iex(3)> Price.to_float(32.0) 
32.0 
iex(4)> Price.to_float("32") 
32.0