gpt4 book ai didi

julia - Julia 1.0 中的逗号任何类型的数字

转载 作者:行者123 更新时间:2023-12-01 07:21:33 26 4
gpt4 key购买 nike

我想要一个 Julia 代码中的函数,num2str,它会在任何类型的有效 Julia 数字的小数点左侧的适当位置添加逗号或指定的分隔符,包括 BigInt 和 BigFloat。它将返回一个用于打印的字符串。

例如:

flt1 = 122234.141567
println("flt1 num2str($flt1) = ", num2str(flt1))
# Expected output is:
flt1 num2str(122234.141567) = 122,234.141567

我想将此函数与 printprintln 内置函数一起使用。

最佳答案

这个问题在 here 中得到了部分回答,即对于整数。以下函数应满足对 float 和“大”数字的需求。

"""
For any valid number, add appropriate delimiters.
See "Regular Expressions Cookbook," by Goyvaerts and Levithan, O'Reilly, 2nd Ed,
p. 402, for Regex that inserts commas into integers returning a string.
"""
function num2str(num::Number; delim=",")
decimal_point = "."
str = string(num)
strs = split(str, decimal_point)
left_str = strs[1]
right_str = length(strs) > 1 ? strs[2] : ""
left_str = replace(left_str, r"(?<=[0-9])(?=(?:[0-9]{3})+(?![0-9]))" => delim)
decimal_point = occursin(decimal_point, str) ? decimal_point : ""
return left_str * decimal_point * right_str
end

# Test integers, BigInts, floats, and BigFloats:
int0 = 0
int1 = 123
int2 = 123456789
big1 = big"123"
big2 = big"123456789123456789"
flt1 = 122234.141567
flt2 = 7.12345e9
big3 = big"260123.0"
big4 = big"7.12345e9"

setprecision(20)
println("int0 num2str($int0) \t\t\t\t = ", num2str(int0))
println("int1 num2str($int1) \t\t\t\t = ", num2str(int1))
println("int2 num2str($int2) \t\t\t = ", num2str(int2))
println("big1 num2str($big1) \t\t\t\t = ", num2str(big1))
println("big2 num2str($big2) \t\t = ", num2str(big2))
println("big2 num2str($big2) delim is _ \t = ", num2str(big2, delim="_"))
println("flt1 num2str($flt1) \t\t\t = ", num2str(flt1))
println("flt1 num2str($flt1) delim is _ \t\t = ", num2str(flt1, delim="_"))
println("flt2 num2str($flt2) \t\t\t = ", num2str(flt2))
println("big3 num2str($big3) \t\t\t = ", num2str(big3))
println("big4 num2str($big4) \t\t\t = ", num2str(big4))
println("big4 num2str($big4) delim is _ \t\t = ", num2str(big4, delim="_"))

## ============================== Output ===================================
int0 num2str(0) = 0
int1 num2str(123) = 123
int2 num2str(123456789) = 123,456,789
big1 num2str(123) = 123
big2 num2str(123456789123456789) = 123,456,789,123,456,789
big2 num2str(123456789123456789) delim is _ = 123_456_789_123_456_789
flt1 num2str(122234.141567) = 122,234.141567
flt1 num2str(122234.141567) delim is _ = 122_234.141567
flt2 num2str(7.12345e9) = 7.12345e9
big3 num2str(2.60123e+05) = 2.60123e+05
big4 num2str(7.12345e+09) = 7.12345e+09
big4 num2str(7.12345e+09) delim is _ = 7.12345e+09

我希望添加逗号分隔符的功能最终会添加到 print/println 和/或 @printf 中。在那之前,这似乎行得通。

关于julia - Julia 1.0 中的逗号任何类型的数字,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52360129/

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