François Huppé
François Huppé

Reputation: 2116

php base_convert not working for non-integers?

I want to write 3.1415 (written under base ten) in base 8 using php.

I'm expecting 3.11034, but base_convert(3.1415,10,8); is returning 75267...

php.net says the first parameter should be a number but it clearly interprets it as an integer.

Upvotes: 1

Views: 477

Answers (1)

user6184150
user6184150

Reputation:

According to the php doc you specified, the base_convert function defined like this:

base_convert ( string $number , int $frombase , int $tobase ) : string

We can see that the $number parameter should be a string, but if we replace the number 3.1415 in your example with string contains the same number, it still doesn't works. But you must pay attention to the parameters specification down in the page:

number - The number to convert. Any invalid characters in number are silently ignored.

Apparently the function ignoring some characters. The most reasonable thing we can think, is that the function maybe consider the decimal point as an invalid character, after all - the function converts the number to string as I mentioned. I ran a test, turns out the function returns 75267 when I set the number to 31415 (without the decimal point).

Conclusion: The function consider the decimal point as a invalid character, and the number can be an Integer only.

Upvotes: 2

Related Questions