This is the new home of the egghelp.org community forum.
All data has been migrated (including user logins/passwords) to a new phpBB version.


For more information, see this announcement post. Click the X in the top right-corner of this box to dismiss this message.

Decimal numbers

Help for those learning Tcl or writing their own scripts.
Post Reply
I
IRCNick
Halfop
Posts: 64
Joined: Wed Oct 12, 2005 9:43 pm
Location: Germany
Contact:

Decimal numbers

Post by IRCNick »

Hi, I have a problem with the decimal numbers. How can make my script to show and calculate decimal numbers ? Should I use the package "Decimal arithmetic" or there is other way to do what I need ?

This is a sample of that what I'm trying to do:

Code: Select all

set a 12; set b 20; set sum [expr ($a + $b)]
set c [expr (($a / 100) * ($sum / 100)) * 100]
set d [expr (($b / 100) * ($sum / 100)) * 100]
User avatar
Sir_Fz
Revered One
Posts: 3794
Joined: Sun Apr 27, 2003 3:10 pm
Location: Lebanon
Contact:

Post by Sir_Fz »

Add a decimal point to the number you're dividing by. For example:

Code: Select all

set c [expr (($a / 100.) * ($sum / 100.)) * 100]
I
IRCNick
Halfop
Posts: 64
Joined: Wed Oct 12, 2005 9:43 pm
Location: Germany
Contact:

Post by IRCNick »

Ok it works, but now I have a double value for the result. How can I convert it to integer ?
User avatar
Sir_Fz
Revered One
Posts: 3794
Joined: Sun Apr 27, 2003 3:10 pm
Location: Lebanon
Contact:

Post by Sir_Fz »

Code: Select all

set result [expr {int($result)}]
I
IRCNick
Halfop
Posts: 64
Joined: Wed Oct 12, 2005 9:43 pm
Location: Germany
Contact:

Post by IRCNick »

Thank you
User avatar
De Kus
Revered One
Posts: 1361
Joined: Sun Dec 15, 2002 11:41 am
Location: Germany

Post by De Kus »

int() will cut off string after the decimal point, round() will do the same, but adding 0.5 before doing so :D.
De Kus
StarZ|De_Kus, De_Kus or DeKus on IRC
Copyright © 2005-2009 by De Kus - published under The MIT License
Love hurts, love strengthens...
User avatar
Sir_Fz
Revered One
Posts: 3794
Joined: Sun Apr 27, 2003 3:10 pm
Location: Lebanon
Contact:

Post by Sir_Fz »

round() will round to the closest number. For example:
% expr round(1.2)
1
% expr round(1.6)
2
floor() will round to the lower and ceil() will round to the greater.
% expr floor(1.6)
1.0
% expr ceil(1.6)
2.0
Post Reply