Is there a datatype “Decimal” in R?

前端 未结 2 415
盖世英雄少女心
盖世英雄少女心 2021-01-04 03:23

I read data stored in the format DECIMAL from a MySQL-Table. I want to do calculations on those numbers within R.

I used to cast them to a numeri repres

2条回答
  •  萌比男神i
    2021-01-04 04:04

    Similar approach to Ari answer but using integer64 class from bit64 package. Using big int as underlying data type for decimal is common practice in various applications that doesn't support decimal type natively.

    library(bit64)
    
    as.decimal = function(x, p=2L) structure(as.integer64(x*10^p), class="decimal", precision=p)
    print.decimal = function(x) print(as.double(x))
    as.integer64.decimal = function(x) structure(x, class="integer64", precision=NULL) # this should not be exported
    as.double.decimal = function(x) as.integer64(x)/(10^attr(x, "precision"))
    is.decimal = function(x) inherits(x, "decimal")
    "==.decimal" = function(e1, e2) `==`(as.integer64(e1), as.integer64(e2))
    "+.decimal" = function(e1, e2) `+`(as.integer64(e1), as.integer64(e2))
    
    d = as.decimal(12.69)
    is.decimal(d)
    #[1] TRUE
    print(d)
    #[1] 12.69
    as.double(d)
    #[1] 12.69
    d + as.decimal(0.9)
    #[1] 13.59
    0.1 + 0.2 == 0.3
    #[1] FALSE
    as.decimal(0.1) + as.decimal(0.2) == as.decimal(0.3)
    #[1] TRUE
    

提交回复
热议问题