R语言 小数位数格式
在这篇文章中,我们将讨论如何在R编程语言中格式化小数点后n位的数字。在R语言中,小数点后的数字用 . 符号表示 。
方法1:Format()函数
Format()函数可用于通过四舍五入来格式化小数值,并在小数点后只显示特定数量的元素。
语法
format(round(value, n), nsmall = n)
参数:
它可以接受两个参数。
- round(value,n) 函数:它将指定要选择的小数位数。它将接受输入的数字和整数值,以选择给定数字的小数位。
- nsmall函数:它将指定要选择的小数位数。它将接受输入的数字以及选择给定数字的小数位数的整数值。
结果:
格式化的小数。
例子
# define an variable and initialize
# to decimal number
a=12.4556785
# display decimal places upto 3
print(format(round(a, 3), nsmall = 3))
# display decimal places upto 4
print(format(round(a, 4), nsmall = 4))
# display decimal places upto 0
print(format(round(a, 0), nsmall = 0))
# display decimal places upto 1
print(format(round(a, 1), nsmall = 1))
输出
例2 :
# define a vector with decimal
# elements
a=c(12.4556785,1.345,6.789,7.890)
# display decimal places upto 3
for (i in a){
print(format(round(i, 3), nsmall = 3))
}
输出
方法2:使用 sprintf() 函数
使用 sprintf() 函数,我们可以指定变量的小数位格式
语法 :sprintf(variable, fmt = ‘%.nf’)
参数
- variable – 输入的十进制数值
- fmt代表格式,它将接受参数”.%nf”,其中n指定要选择的小数位数。
结果 :
格式化的十进制数字
例1 :
# decimal number
a=14.6788
# format upto 4 places
print( sprintf(a, fmt = '%.4f') )
# format upto 8 places
print( sprintf(a, fmt = '%.8f') )
# format upto 1 place
print( sprintf(a, fmt = '%.1f') )
# format upto 0 places
print( sprintf(a, fmt = '%.0f') )
输出
例2 :
# define a vector with decimal elements
a=c(12.4556785,1.345,6.789,7.89089)
# display decimal places upto 4
for (i in a){
print( sprintf(i, fmt = '%.4f') )
}
print("---------------------")
# display decimal places upto 1
for (i in a){
print( sprintf(i, fmt = '%.1f') )
}
print("---------------------")
# display decimal places upto 2
for (i in a){
print( sprintf(i, fmt = '%.2f') )
}
print("---------------------")
# display decimal places upto 0
for (i in a){
print( sprintf(i, fmt = '%.0f') )
}
输出
方法3:使用options()函数
该函数用于返回小数点后的数字。
语法
options(digits = n)
其中digits是要返回的数字,以及小数点前的数字。
例子
a=1.24325454666
options(digits=4)
它将返回1.243
例子1 :
# decimal number
a=14.67885350938953809580
# format upto 4 places
options(digits=4)
print(a)
# format upto 8 places
options(digits=8)
print(a)
# format upto 3 place
options(digits=3)
print(a)
输出
例2 :
# define a vector with decimal elements
a=c(12.4556785,1.345,6.789,7.89089)
# display decimal places upto 4
options(digits=4)
for (i in a){
print( i )
}
print("---------------------")
# display decimal places upto 6
options(digits=6)
for (i in a){
print( i )
}
print("---------------------")
# display decimal places upto 2
options(digits=2)
for (i in a){
print( i )
}
输出