Get floating / decimal float plot

I would like to:

unknown_function(123.456) -> 456
unknown_function(1234.56) -> 56

      

or

unknown_function(123.456) -> "456"

      

Is there a built in one for this? The inline trunc/1

does the opposite:

2> trunc(123.456).
123

      

There is this answer for C: Extract the decimal part from a floating point number in C and this is for Java: How to get the decimal part of a float?

+3


source to share


3 answers


This is inspired by @ Dogbert's comment

The algorithm does not work using native floats due to floating point limits and rounding errors.

However, using https://github.com/tim/erlang-decimal :

frac_to_denom_int(Num, Denom, Precison) ->
{X, _} = string:to_integer(lists:nth(2, string:tokens(decimal:format(decimal:divide(Num, Denom, [{precision, Precison}])), "."))),
X.

      



eg.

frac_to_denom_int("1.0", "3.0", 1000).
> 3333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333

      

If you do not have hydraulic fracturing,

d_to_denom_int(D_Tup)->
    string:to_integer(lists:nth(2, string:tokens(decimal:format(D_Tup), "."))).

d_to_denom_int({0, 123456, -3}).
 > 456

      

0


source


No, there is no BIF for this, but you can do this:



decimal_point(X, DecimalDigits) when X < 0 ->
  decimal_point(-X, DecimalDigits);
decimal_point(X, DecimalDigits)->
  (X - trunc(X)) * math:pow(10,DecimalDigits).

> decimal_point(2.33, 2).
33
> decimal_point(-2.33, 2).
33

      

+1


source


Based on @dogbert's comment, passing another flag compact

in the call float_to_list/2

would help:

lists:nth(2, string:tokens(float_to_list(123.456, [{decimals, 10}, compact]), ".")).
% "456"

      

If you go through 14 decimal places, you will start to see these rounding errors.

0


source







All Articles