简体   繁体   English

将数字转换为科学格式的字符串

[英]Convert number to string in scientific format

I have some numbers, such as num = c(0.1, 0.001, 1.12345e-5) . 我有一些数字,例如num = c(0.1, 0.001, 1.12345e-5) I want to turn num as string, with each element displayed in scientific format, with 3 digits. 我想将num作为字符串,每个元素以科学格式显示,有3位数字。 That is num_after_convert = c( '1.00e-1', '1.00e-3' , '1.12e-5') . 这是num_after_convert = c( '1.00e-1', '1.00e-3' , '1.12e-5') Any good solution? 有什么好办法吗?

The sprintf function will give you the most control of the output and can guarantee scientific notation: sprintf函数将为您提供最大的输出控制,并可以保证科学记数:

> num <- c(0.1, 0.001, 1.12345e-5)
> sprintf("%4.2e", num)
[1] "1.00e-01" "1.00e-03" "1.12e-05"
> 

如果你的矢量总是至少有一个元素已经用科学记数法,请尝试这个,如你的例子:

format(num,digits=3)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM