lokheart
lokheart

Reputation: 24665

How to make "pretty rounding"?

I need to do a rounding like this and convert it as a character:

as.character(round(5.9999,2))

I expect it to become 6.00, but it just gives me 6

Is there anyway that I can make it show 6.00?

Upvotes: 9

Views: 1877

Answers (3)

Vishal Lala
Vishal Lala

Reputation: 49

As Dirk indicated, formatC() is another option.

formatC(x = 5.999, digits = 2, format = 'f')

Upvotes: -1

Ken Williams
Ken Williams

Reputation: 23975

To help explain what's going on - the round(5.9999, 2) call is rounding your number to the nearest hundredths place, which gives you the number (not string) very close to (or exactly equal to, if you get lucky with floating-point representations) 6.00. Then as.character() looks at that number, takes up to 15 significant digits of it (see ?as.character) in order to represent it to sufficient accuracy, and determines that only 1 significant digit is necessary. So that's what you get.

Upvotes: 2

Dirk is no longer here
Dirk is no longer here

Reputation: 368241

Try either one of these:

> sprintf("%3.2f", round(5.9999, digits=2))
[1] "6.00
> sprintf("%3.2f", 5.999)  # no round needed either
[1] "6.00

There are also formatC() and prettyNum().

Upvotes: 11

Related Questions