julia:String:转化和输出格式化

本文详细介绍了如何在编程中将字符串转化为浮点数、整数,并将其格式化为固定精度的小数、科学计数法等多种形式。通过具体示例展示了如何使用printf和sprintf等函数进行数字与字符串的相互转换及格式设定。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

# String: 转化和格式化
# strings can be converted using float and Int
e_str1 = "2.718"
e = float(e_str1)
println(5*e)
#> 13.5914
num_15 = parse(Int, "15") # 对于整数的字符串,需要Int与parse配合使用
println(3*num_15)
#> 45

# numbers can be converted to strings and formatted using printf
@printf "e = %0.2f\n" e
#> 2.72
# or to create another string sprintf
e_str2 = @sprintf("%0.3f", e)  # 返回值为字符串

# to show that the 2 strings are the same
println("e_str1 == s_str2: $(e_str1 == e_str2)")
#> e_str1 == s_str2: true

# available number format characters are f, e, g, c, s, p, d:
# (pi is a predefined constant; however, since its type is
# "MathConst" it has to be converted to a float to be formatted)
@printf "fix trailing precision: %0.3f\n" float(pi)
#> fix trailing precision: 3.142
@printf "scientific form: %0.6e\n" 1000pi
#> scientific form: 3.141593e+03
# g is not implemented yet
@printf "a character: %c\n" 'α'
#> a character: α
@printf "a string: %s\n" "look I'm a string!"
#> a string: look I'm a string!
@printf "right justify a string: %50s\n" "width 50, text right justified!"
#> right justify a string:                    width 50, text right justified!
@printf "a pointer: %p\n" 100000000
#> a pointer: 0x0000000005f5e100
@printf "print a integer: %d\n" 1e10
#> print an integer: 10000000000

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值