SlideShare a Scribd company logo
Perfectly Problematic PHP Precision
Or “Dude Where's My Digits?”
About the precision of floating point numbers in PHP
By Daniel Rhodes
Of Warp Asylum Ltd
http://www.warpasylum.co.uk
Floating what now?
● A floating point number is how we store fractional
numbers in computing
● For example, 1.23, 3.1415, 0.05 all need to be stored
as floating point numbers
● The decimal point “floats” as we can store different
sized whole parts and different accuracies of the
fractional part. For example 34535345345.2 or
2.6745354677
OK, so how do we do this in PHP?
● Well, our first little problemette is that PHP is
mostly untyped. The same PHP variable can hold a
string or a number. The variable will be treated as
numbery if it looks like a number, else it will be
treated as stringy.
● This is actually quite useful given that Hyper TEXT
transfer protocol is PHP's biggest context.
● But in our case...
Floating point variables
●
$float = (float) 3.1415; //cast from numeric
●
$float = (float) '3.1415'; //cast from string
●
$float = floatval(3.1415); //get float value
●
$float = floatval('3.1415'); //get float value
●
$float = '3.1415'; settype($float, 'float'); //set as
● After any of the above, $float will be internally
represented as an actual floating point number
Advanced problems
● OK, that's the basics finished. But there's another,
less obvious problem to be aware of.
● Let's say we want to add metrics recording (of every
button and link clicked for example) to our website,
and we want to save each click event with its
timestamp in our NoSQL database...
UNIX timestamp with microseconds
● According to php.net, microtime(true) will return
the current UNIX timestamp – down to microsecond
(ie. 6 digit) accuracy – as a float.
● Let's give it a whirl:
● $ts = microtime(true); echo $ts;
● Gives: 1379523470.4252
● This is not 6 digit accuracy!
Dude where's my digits?
● The good news is that internally we do indeed have
6 digits
● The bad news is that, because we used echo, our
float got converted to a stringy format which means
that some dark, mysterious forces come into play.
Namely...
● The precision directive in php.ini [or ini_set()]
Peculiar PHP precision
● The little-know precision directive sets the
maximum precision of floats when echoed or stored
as stringy.
● The current default is 14 (2 less than we need for
microsecond timestamps)
● Kicks in when you (or PHP!) echo(), print(), cast
as string or json_encode() a float variable
● Set it in php.ini or with ini_set('precision', 16)
Increasing the precision
● OK, let's try our timestamp example again but with
increased precision:
● ini_set('precision', 16); $ts = microtime(true); echo
$ts;
● Gives: 1379525237.5543571
● 6 digits!
An interesting exception
● As mentioned, echo() and json_encode() etc will
use the precision directive
● BUT the stringy sprintf() family of functions do not
use the precision directive
● Let's try it:
● $ts = microtime(true); echo sprintf(“%f”, $ts);
● Gives: 1379534265.381266
● Nice!
About sprintf()
●
sprintf(“%f”, $x) defaults to 6 decimal digits
● But we can specify the precision with, for example,
sprintf(“%0.8f”, $x) for 8 decimal digits
● So, if appropriate, we can use this instead of
tinkering with the precision directive
Summary
● Floating point variables will have precision applied
when made stringy by whatever means
●
precision specifies the total number of digits to
print – before and after the point
●
precision is easily changed in php.ini or with
ini_set()
●
sprintf() [and related] does not apply precision
and is configurable per use
Further reading
● http://php.net/manual/en/language.types.type-juggling.php
● http://www.php.net/manual/en/language.types.float.php
● http://floating-point-gui.de (float arithmetic)
● http://www.php.net/manual/en/ini.core.php#ini.serialize-precision
● http://www.leaseweblabs.com/2013/06/the-php-floating-point-precision-is-wrong-by-default
●

More Related Content

PDF
Zeromq anatomy & jeromq
PPTX
Php training in chandigarh
PDF
[Curso Java Basico] Aula 57: Wrappers: classes de tipos primitivos
PDF
ZeroMQ - Sockets on steroids!
ODP
Tecnologi lenguatge
PPTX
Polymorphism in c++
PPT
C++ programming
PDF
PPU Optimisation Lesson
Zeromq anatomy & jeromq
Php training in chandigarh
[Curso Java Basico] Aula 57: Wrappers: classes de tipos primitivos
ZeroMQ - Sockets on steroids!
Tecnologi lenguatge
Polymorphism in c++
C++ programming
PPU Optimisation Lesson

What's hot (19)

PDF
Algorithm and Programming (Looping Structure)
PDF
C++ Course - Lesson 1
PPTX
Final requirement in programming niperos
PPT
170120107074 looping statements and nesting of loop statements
PPTX
03loop conditional statements
ODP
CISSP Week 18
PDF
Programming
PPTX
Cryptography
PPSX
C lecture 4 nested loops and jumping statements slideshare
PDF
Computer Security (Cryptography) Ch02
PDF
Programming with Python - Adv.
PPTX
Do...while loop structure
PDF
Thrfit从入门到精通
PDF
Applied cryptanalysis - everything else
PPTX
TypeScript, Now.
PPTX
Looping statement
PPTX
Switch case and looping
PPTX
MATLAB Programming - Loop Control Part 2
Algorithm and Programming (Looping Structure)
C++ Course - Lesson 1
Final requirement in programming niperos
170120107074 looping statements and nesting of loop statements
03loop conditional statements
CISSP Week 18
Programming
Cryptography
C lecture 4 nested loops and jumping statements slideshare
Computer Security (Cryptography) Ch02
Programming with Python - Adv.
Do...while loop structure
Thrfit从入门到精通
Applied cryptanalysis - everything else
TypeScript, Now.
Looping statement
Switch case and looping
MATLAB Programming - Loop Control Part 2
Ad

Similar to PHP floating point precision (20)

PDF
PDF
Microcontroladores: Programación en C para microcontroladores con AVR Butterf...
PPTX
Simplifying training deep and serving learning models with big data in python...
PPT
CPAP.com Introduction To Coding: Part 2
PDF
Programming in PHP Course Material BCA 6th Semester
PPTX
PDF
An SEO’s Intro to Web Dev PHP
PPTX
Kaggle Tweet Sentiment Extraction: 1st place solution
PPTX
Php operators
PDF
Php web development
PPTX
Powering Tensorflow with big data using Apache Beam, Flink, and Spark - OSCON...
PPTX
Lesson 3 php numbers
PDF
Nullcon Hack IM 2011 walk through
DOC
PHP MATERIAL
PPT
Php, mysq lpart1
PPTX
Introduction to Python Part-1
PPT
PHP CONDITIONAL STATEMENTS AND LOOPING.ppt
PPT
What Is Php
 
PPT
PHP - Web Development
PPTX
Going loopy - Introduction to Loops.pptx
Microcontroladores: Programación en C para microcontroladores con AVR Butterf...
Simplifying training deep and serving learning models with big data in python...
CPAP.com Introduction To Coding: Part 2
Programming in PHP Course Material BCA 6th Semester
An SEO’s Intro to Web Dev PHP
Kaggle Tweet Sentiment Extraction: 1st place solution
Php operators
Php web development
Powering Tensorflow with big data using Apache Beam, Flink, and Spark - OSCON...
Lesson 3 php numbers
Nullcon Hack IM 2011 walk through
PHP MATERIAL
Php, mysq lpart1
Introduction to Python Part-1
PHP CONDITIONAL STATEMENTS AND LOOPING.ppt
What Is Php
 
PHP - Web Development
Going loopy - Introduction to Loops.pptx
Ad

More from Daniel_Rhodes (9)

PDF
PhoneGap by Dissection
ODP
Hyperlocalisation or "localising everything"
PPT
Creating a constructive comment culture
PDF
"Internationalisation with PHP and Intl" source code
ODP
Internationalisation with PHP and Intl
ODP
Character sets and iconv
PDF
"Character sets and iconv" PHP source code
ODP
Handling multibyte CSV files in PHP
ODP
Multibyte string handling in PHP
PhoneGap by Dissection
Hyperlocalisation or "localising everything"
Creating a constructive comment culture
"Internationalisation with PHP and Intl" source code
Internationalisation with PHP and Intl
Character sets and iconv
"Character sets and iconv" PHP source code
Handling multibyte CSV files in PHP
Multibyte string handling in PHP

Recently uploaded (20)

PPTX
Spectroscopy.pptx food analysis technology
PPTX
VMware vSphere Foundation How to Sell Presentation-Ver1.4-2-14-2024.pptx
PDF
Unlocking AI with Model Context Protocol (MCP)
PPTX
Effective Security Operations Center (SOC) A Modern, Strategic, and Threat-In...
PDF
Optimiser vos workloads AI/ML sur Amazon EC2 et AWS Graviton
PPTX
KOM of Painting work and Equipment Insulation REV00 update 25-dec.pptx
PDF
MIND Revenue Release Quarter 2 2025 Press Release
PDF
Approach and Philosophy of On baking technology
PDF
7 ChatGPT Prompts to Help You Define Your Ideal Customer Profile.pdf
PDF
KodekX | Application Modernization Development
PDF
Profit Center Accounting in SAP S/4HANA, S4F28 Col11
PPT
Teaching material agriculture food technology
PPT
“AI and Expert System Decision Support & Business Intelligence Systems”
PPTX
20250228 LYD VKU AI Blended-Learning.pptx
PDF
Blue Purple Modern Animated Computer Science Presentation.pdf.pdf
PDF
Dropbox Q2 2025 Financial Results & Investor Presentation
PDF
NewMind AI Weekly Chronicles - August'25 Week I
PDF
Review of recent advances in non-invasive hemoglobin estimation
PDF
Machine learning based COVID-19 study performance prediction
PDF
Agricultural_Statistics_at_a_Glance_2022_0.pdf
Spectroscopy.pptx food analysis technology
VMware vSphere Foundation How to Sell Presentation-Ver1.4-2-14-2024.pptx
Unlocking AI with Model Context Protocol (MCP)
Effective Security Operations Center (SOC) A Modern, Strategic, and Threat-In...
Optimiser vos workloads AI/ML sur Amazon EC2 et AWS Graviton
KOM of Painting work and Equipment Insulation REV00 update 25-dec.pptx
MIND Revenue Release Quarter 2 2025 Press Release
Approach and Philosophy of On baking technology
7 ChatGPT Prompts to Help You Define Your Ideal Customer Profile.pdf
KodekX | Application Modernization Development
Profit Center Accounting in SAP S/4HANA, S4F28 Col11
Teaching material agriculture food technology
“AI and Expert System Decision Support & Business Intelligence Systems”
20250228 LYD VKU AI Blended-Learning.pptx
Blue Purple Modern Animated Computer Science Presentation.pdf.pdf
Dropbox Q2 2025 Financial Results & Investor Presentation
NewMind AI Weekly Chronicles - August'25 Week I
Review of recent advances in non-invasive hemoglobin estimation
Machine learning based COVID-19 study performance prediction
Agricultural_Statistics_at_a_Glance_2022_0.pdf

PHP floating point precision

  • 1. Perfectly Problematic PHP Precision Or “Dude Where's My Digits?” About the precision of floating point numbers in PHP By Daniel Rhodes Of Warp Asylum Ltd http://www.warpasylum.co.uk
  • 2. Floating what now? ● A floating point number is how we store fractional numbers in computing ● For example, 1.23, 3.1415, 0.05 all need to be stored as floating point numbers ● The decimal point “floats” as we can store different sized whole parts and different accuracies of the fractional part. For example 34535345345.2 or 2.6745354677
  • 3. OK, so how do we do this in PHP? ● Well, our first little problemette is that PHP is mostly untyped. The same PHP variable can hold a string or a number. The variable will be treated as numbery if it looks like a number, else it will be treated as stringy. ● This is actually quite useful given that Hyper TEXT transfer protocol is PHP's biggest context. ● But in our case...
  • 4. Floating point variables ● $float = (float) 3.1415; //cast from numeric ● $float = (float) '3.1415'; //cast from string ● $float = floatval(3.1415); //get float value ● $float = floatval('3.1415'); //get float value ● $float = '3.1415'; settype($float, 'float'); //set as ● After any of the above, $float will be internally represented as an actual floating point number
  • 5. Advanced problems ● OK, that's the basics finished. But there's another, less obvious problem to be aware of. ● Let's say we want to add metrics recording (of every button and link clicked for example) to our website, and we want to save each click event with its timestamp in our NoSQL database...
  • 6. UNIX timestamp with microseconds ● According to php.net, microtime(true) will return the current UNIX timestamp – down to microsecond (ie. 6 digit) accuracy – as a float. ● Let's give it a whirl: ● $ts = microtime(true); echo $ts; ● Gives: 1379523470.4252 ● This is not 6 digit accuracy!
  • 7. Dude where's my digits? ● The good news is that internally we do indeed have 6 digits ● The bad news is that, because we used echo, our float got converted to a stringy format which means that some dark, mysterious forces come into play. Namely... ● The precision directive in php.ini [or ini_set()]
  • 8. Peculiar PHP precision ● The little-know precision directive sets the maximum precision of floats when echoed or stored as stringy. ● The current default is 14 (2 less than we need for microsecond timestamps) ● Kicks in when you (or PHP!) echo(), print(), cast as string or json_encode() a float variable ● Set it in php.ini or with ini_set('precision', 16)
  • 9. Increasing the precision ● OK, let's try our timestamp example again but with increased precision: ● ini_set('precision', 16); $ts = microtime(true); echo $ts; ● Gives: 1379525237.5543571 ● 6 digits!
  • 10. An interesting exception ● As mentioned, echo() and json_encode() etc will use the precision directive ● BUT the stringy sprintf() family of functions do not use the precision directive ● Let's try it: ● $ts = microtime(true); echo sprintf(“%f”, $ts); ● Gives: 1379534265.381266 ● Nice!
  • 11. About sprintf() ● sprintf(“%f”, $x) defaults to 6 decimal digits ● But we can specify the precision with, for example, sprintf(“%0.8f”, $x) for 8 decimal digits ● So, if appropriate, we can use this instead of tinkering with the precision directive
  • 12. Summary ● Floating point variables will have precision applied when made stringy by whatever means ● precision specifies the total number of digits to print – before and after the point ● precision is easily changed in php.ini or with ini_set() ● sprintf() [and related] does not apply precision and is configurable per use
  • 13. Further reading ● http://php.net/manual/en/language.types.type-juggling.php ● http://www.php.net/manual/en/language.types.float.php ● http://floating-point-gui.de (float arithmetic) ● http://www.php.net/manual/en/ini.core.php#ini.serialize-precision ● http://www.leaseweblabs.com/2013/06/the-php-floating-point-precision-is-wrong-by-default ●