Constants in Erlang

Our program will demonstrate the use of constants, which can be of character, string, boolean, and numeric values. Here’s the full source code translated to Erlang.

-module(constants).
-export([main/0]).

main() ->
    %% Declaring a string constant
    S = "constant",
    io:format("~p~n", [S]),

    %% Declaring a numeric constant
    N = 500000000,
    io:format("~p~n", [N]),

    %% Performing arithmetic with arbitrary precision
    D = 3.0e20 / N,
    io:format("~p~n", [D]),

    %% Explicitly converting the result to int
    io:format("~p~n", [erlang:round(D)]),

    %% Using the number in a context that expects a float
    SinN = math:sin(N),
    io:format("~p~n", [SinN]).

To run the Erlang program, save the above code into a file named constants.erl, then compile and execute it using the erl shell:

$ erlc constants.erl
$ erl -noshell -s constants main -s init stop
"constant"
500000000
6.0e+11
600000000000
-0.28470407323754404

This example illustrates how constants can be used in Erlang, how to perform arithmetic with them, and how to work with their types. Now that we know how to handle constants in Erlang, let’s learn more about other essential language features.