algorithm - Get number of digits in an unsigned long integer c# -
i'm trying determine number of digits in c# ulong number, i'm trying using math logic rather using tostring().length. have not benchmarked 2 approaches have seen other posts using system.math.floor(system.math.log10(number)) + 1 determine number of digits. seems work fine until transition 999999999999997 999999999999998 @ point, start getting incorrect count.
has encountered issue before ?
i have seen similar posts java emphasis @ why log(1000)/log(10) isn't same log10(1000)? , post @ how separate digits of int number? indicates how possibly achieve same using % operator lot more code
here code used simulate this
action<ulong> displayinfo = number => console.writeline("{0,-20} {1,-20} {2,-20} {3,-20} {4,-20}", number, number.tostring().length, system.math.log10(number), system.math.floor(system.math.log10(number)), system.math.floor(system.math.log10(number)) + 1); array.foreach(new ulong[] { 9u, 99u, 999u, 9999u, 99999u, 999999u, 9999999u, 99999999u, 999999999u, 9999999999u, 99999999999u, 999999999999u, 9999999999999u, 99999999999999u, 999999999999999u, 9999999999999999u, 99999999999999999u, 999999999999999999u, 9999999999999999999u}, displayinfo); array.foreach(new ulong[] { 1u, 19u, 199u, 1999u, 19999u, 199999u, 1999999u, 19999999u, 199999999u, 1999999999u, 19999999999u, 199999999999u, 1999999999999u, 19999999999999u, 199999999999999u, 1999999999999999u, 19999999999999999u, 199999999999999999u, 1999999999999999999u }, displayinfo);
thanks in advance
pat
log10 going involve floating point conversion - hence rounding error. error pretty small double, big deal exact integer!
excluding .tostring() method , floating point method, yes think going have use iterative method use integer divide rather modulo.
integer divide 10. result>0? if iterate around. if not, stop. number of digits number of iterations required.
eg. 5 -> 0; 1 iteration = 1 digit.
1234 -> 123 -> 12 -> 1 -> 0; 4 iterations = 4 digits.
Comments
Post a Comment