Skip to content
Tcl Source Code View Ticket
Login

View Ticket

2012-09-05
17:44 • Closed ticket [3564821fff]: math rounding function with arbitrary decimal precis... artifact: a853cfee37 user: sebres
17:21 • Ticket [3564821fff]: 4 changes artifact: ec616519e0 user: jmcuaz
16:16 • Ticket [3564821fff]: 4 changes artifact: 2a16c826c2 user: sebres
2012-09-04
21:22 • New ticket [3564821fff]. artifact: 5a4e18d522 user: jmcuaz

math rounding function with arbitrary decimal precision

Closed / Accepted3564821fffffffffffffffffffffffffffffffffCreated 14 years agoUpdated 14 years ago
Descriptionplain2012-09-04 21:22:46
When dealing with floating point numbers, there is no easy way in tcl to do something like "round( 2.125 , 2 )" with an expected return of 2.13

For the choice of upward/downward rounding (i.e. toward inf+ or inf-) and to disambiguate the semantic of rounding on negatives fp numbers, maybe two separate functions would be good : something like 
roundup(x,y)  -> toward inf+
rounddown(x,y) -> toward inf-

Regards

Jean-Marie Cuaz
sebresplain2012-09-05 16:16:48
Why can you not use "format" like this?
% format %.2f 2.125
2.13

And if you really need a mathematical function, you can simple create it self, something like this:
% proc ::tcl::mathfunc::roundup {n e} {double [format %.${e}f $n]}
% puts [expr roundup( 2.555, 2 )]
2.56
jmcuazplain2012-09-05 17:21:19
You are right.
format f does an arithmetical rounding and not the simple truncation I understood when reading the doc : <quote>  For e, E, and f conversions it specifies the number of digits to appear to the right of the decimal point. <end of quote>.

Sorry for the nuisance and thanks for the clarification

Regards

Jean-Marie
sebres Closed ticket [3564821fff]. [History diff]2012-09-05 17:44:50
Log in (anonymous is fine) to add a comment.