Sometimes rounding number are not consistent [dupl

2020-07-06 09:06发布

Please can you help to solve this issue:

round(30.5)
[1] 30 
round(31.5)
[1] 32

I want to get always 0.5s either up or down. Any solution

标签: r
2条回答
▲ chillily
2楼-- · 2020-07-06 09:07

This is yet another instance of R-FAQ 7.31 (link to the FAQ on your device) ...... (link to the CRAN version). If you always want floating point numbers that are displayed by print.default as x.5 to "round up" then you need to add a bit of "fuzz". I chose that amount of fuzz to be similar to the accuracy with which print.default usually displays numbers.

  >  round(30.5 +0.00000001)
[1] 31

To make this happen in a function:

> round.up <- function(x, digits=0) round(x+0.00000001, digits)
> round.up(30.5)

You might also ponder this:

> 31.5==31.50000000000000001
[1] TRUE
> 31.5==31.5000000000000001
[1] TRUE
> 31.5==31.500000000000001
[1] TRUE
> 31.5==31.50000000000001
[1] FALSE

>  31.50000000000001
[1] 31.5

> 31.50000001
[1] 31.5
> 31.50001
[1] 31.50001
查看更多
冷血范
3楼-- · 2020-07-06 09:28

A solution that does not need a print-format dependent offset:

To always round up, use

ceiling(x - 0.5)

To always round down, use

floor(x + 0.5)
查看更多
登录 后发表回答