gpt4 book ai didi

elixir - 在 Phoenix Framework 中为整数添加分隔符

转载 作者:行者123 更新时间:2023-12-02 07:25:15 25 4
gpt4 key购买 nike

所以假设我有一个像 123456789 这样的数字,我想将它转换为一个字符串,并将其显示为 123,456,789123 456 789 等。最好的方法是什么?

最佳答案

我不认为有一种内置的方式。对于一般格式,您可以使用 :io.format/2 这是一种方法:

123456789
|> Integer.to_char_list
|> Enum.reverse
|> Enum.chunk_every(3)
|> Enum.join(",")
|> String.reverse

# "123,456,789"
编辑:这是一个也适用于小数的解决方案。它可以选择允许设置自定义分隔符:
defmodule Formatter do
@doc """
## Examples

iex> Formatter.format_number(1)
"1"

iex> Formatter.format_number(123)
"123"

iex> Formatter.format_number(1234)
"1,234"

iex> Formatter.format_number(123456789)
"123,456,789"

iex> Formatter.format_number(-123456789)
"-123,456,789"

iex> Formatter.format_number(12345.6789)
"12,345.6789"

iex> Formatter.format_number(-12345.6789)
"-12,345.6789"

iex> Formatter.format_number(123456789, thousands_separator: "")
"123456789"

iex> Formatter.format_number(-123456789, thousands_separator: "")
"-123456789"

iex> Formatter.format_number(12345.6789, thousands_separator: "")
"12345.6789"

iex> Formatter.format_number(-12345.6789, thousands_separator: "")
"-12345.6789"

iex> Formatter.format_number(123456789, decimal_separator: ",", thousands_separator: ".")
"123.456.789"

iex> Formatter.format_number(-123456789, decimal_separator: ",", thousands_separator: ".")
"-123.456.789"

iex> Formatter.format_number(12345.6789, decimal_separator: ",", thousands_separator: ".")
"12.345,6789"

iex> Formatter.format_number(-12345.6789, decimal_separator: ",", thousands_separator: ".")
"-12.345,6789"
"""

@regex ~r/(?<sign>-?)(?<int>\d+)(\.(?<frac>\d+))?/

def format_number(number, options \\ []) do
thousands_separator = Keyword.get(options, :thousands_separator, ",")
parts = Regex.named_captures(@regex, to_string(number))

formatted_int =
parts["int"]
|> String.graphemes
|> Enum.reverse
|> Enum.chunk_every(3)
|> Enum.join(thousands_separator)
|> String.reverse

decimal_separator =
if parts["frac"] == "" do
""
else
Keyword.get(options, :decimal_separator, ".")
end

to_string [parts["sign"], formatted_int, decimal_separator, parts["frac"]]
end
end

关于elixir - 在 Phoenix Framework 中为整数添加分隔符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33184420/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com