Finding The Number Of Digits In A Number Part 2
Finding the number of digits in a number using math functions.
Here we are going to write a file named digitcountp2.tcl and then we will run it as,
tclsh digitcountp2.tcl
#digitcountp2.tcl
# The number of digits in a number.
proc dcnt {num} {
set number $num;
set digicnt 0;
if {$number != 0} {
if {$number < 0} {
set number [expr {$number * -1}];
}
set digicnt [expr {floor(log10($number) + 1)}];
}
return $digicnt;
}
#Examples
puts "Number of digits in 00: [dcnt 00]";
puts "Number of digits in 2019: [dcnt 2019]";
puts "Number of digits in -123: [dcnt -123]";
Happy reading and thank you. Meet you soon.
Comments
Post a Comment