开发者

Best method to deal with numbers? Getting and changing individual digits

I want to take a 1 to 17 digit number, then put it through a series of logic loops that will change various digits of the number. I need to be able to do the following:

1) A quick way to know how many digits there are in the number. Is there a good (efficient) php method to do this? Is getting log base 10 the best way? Or maybe turning it into a string and asking for the length?

2) Next, I need to know what number is in each digit. Should I just keep doing % 10 on the number to parse each digit (doing this would also help solve problem number 1 by开发者_Go百科 adding a count in the loop)?

3) Finally, I need a good way to change the various digits of the number. Should I use regex? Or should I just build up a new number by adding various numbers together, with each number representing the digit (ex. 1 + 30 + 400 + 2000 + 6000 = 62431)? I guess I could also adjust the original number in the same method as the last example by adding/subtracting from it to adjust each digit to the one I want.

Please let me know about other ways to solve my problem if you feel they're faster. Efficiency is key.


I decided to write an answer because the currently accepted one is simply wrong. The relative precision of double numbers is of the order of 1E-16. This is not a limitation of PHP, this is an intrinsic feature of IEEE 754 double. Hence, if you want to manipulate the 17-th digit of a double number, no matter what the magnitude of the number is, using logs and performing arithmetical operations will not do. What you need to do is to convert the number to the string, manipulate the digits in the string and display it from the string, without converting it back to double.


You can change the value of a digit in a number with something like the following:

function numlen($number) { return strlen($number); }

function numAt($number, $index) { return substr($number, $index, 1); }

function changeNumAt($number, $index, $newDigit) {
    return substr_replace($number, $newDigit, $index, 1);
}

For your situation, using the number as a string for a one time number change makes the most sense. To save time, if you will be changing multiple digits you should parse the number into an array of digits. Let me know in the comments if you would like help with doing this.


Simple Benchmarking example:

$start = microtime(true); //Log the start timestamp (including microseconds)
//Do stuff to benchmark
$end = microtime(true); //Log the end timestamp (including microseconds)
echo ((string)($end-$start))."seconds \n";

Use microtime(true) to get the timestamp with microseconds as a float (that's what the true is for). Get the time before and after the action and subtract them to get the total time.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜