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

What's hot

Algorithm and Programming (Looping Structure)
Algorithm and Programming (Looping Structure)Algorithm and Programming (Looping Structure)
Algorithm and Programming (Looping Structure)
Adam Mukharil Bachtiar
 
C++ Course - Lesson 1
C++ Course - Lesson 1C++ Course - Lesson 1
C++ Course - Lesson 1
Mohamed Ahmed
 
Final requirement in programming niperos
Final requirement in programming   niperosFinal requirement in programming   niperos
Final requirement in programming niperosmarkings17
 
170120107074 looping statements and nesting of loop statements
170120107074 looping statements and nesting of loop statements170120107074 looping statements and nesting of loop statements
170120107074 looping statements and nesting of loop statements
harsh kothari
 
03loop conditional statements
03loop conditional statements03loop conditional statements
03loop conditional statements
Abdul Samad
 
CISSP Week 18
CISSP Week 18CISSP Week 18
CISSP Week 18jemtallon
 
Programming
ProgrammingProgramming
Programming
Jamia Hamdard
 
Cryptography
CryptographyCryptography
Cryptography
LAKHI CHAND SINGH
 
C lecture 4 nested loops and jumping statements slideshare
C lecture 4 nested loops and jumping statements slideshareC lecture 4 nested loops and jumping statements slideshare
C lecture 4 nested loops and jumping statements slideshare
Gagan Deep
 
Computer Security (Cryptography) Ch02
Computer Security (Cryptography) Ch02Computer Security (Cryptography) Ch02
Computer Security (Cryptography) Ch02
Saif Kassim
 
Programming with Python - Adv.
Programming with Python - Adv.Programming with Python - Adv.
Programming with Python - Adv.
Mosky Liu
 
Do...while loop structure
Do...while loop structureDo...while loop structure
Do...while loop structureJd Mercado
 
Thrfit从入门到精通
Thrfit从入门到精通Thrfit从入门到精通
Thrfit从入门到精通
炜龙 何
 
Applied cryptanalysis - everything else
Applied cryptanalysis - everything elseApplied cryptanalysis - everything else
Applied cryptanalysis - everything else
Vlad Garbuz
 
TypeScript, Now.
TypeScript, Now.TypeScript, Now.
TypeScript, Now.
Suthep Sangvirotjanaphat
 
Looping statement
Looping statementLooping statement
Looping statementilakkiya
 
Switch case and looping
Switch case and loopingSwitch case and looping
Switch case and loopingaprilyyy
 
MATLAB Programming - Loop Control Part 2
MATLAB Programming - Loop Control Part 2MATLAB Programming - Loop Control Part 2
MATLAB Programming - Loop Control Part 2
Shameer Ahmed Koya
 

What's hot (19)

Algorithm and Programming (Looping Structure)
Algorithm and Programming (Looping Structure)Algorithm and Programming (Looping Structure)
Algorithm and Programming (Looping Structure)
 
C++ Course - Lesson 1
C++ Course - Lesson 1C++ Course - Lesson 1
C++ Course - Lesson 1
 
Final requirement in programming niperos
Final requirement in programming   niperosFinal requirement in programming   niperos
Final requirement in programming niperos
 
170120107074 looping statements and nesting of loop statements
170120107074 looping statements and nesting of loop statements170120107074 looping statements and nesting of loop statements
170120107074 looping statements and nesting of loop statements
 
03loop conditional statements
03loop conditional statements03loop conditional statements
03loop conditional statements
 
CISSP Week 18
CISSP Week 18CISSP Week 18
CISSP Week 18
 
Programming
ProgrammingProgramming
Programming
 
Cryptography
CryptographyCryptography
Cryptography
 
C lecture 4 nested loops and jumping statements slideshare
C lecture 4 nested loops and jumping statements slideshareC lecture 4 nested loops and jumping statements slideshare
C lecture 4 nested loops and jumping statements slideshare
 
Computer Security (Cryptography) Ch02
Computer Security (Cryptography) Ch02Computer Security (Cryptography) Ch02
Computer Security (Cryptography) Ch02
 
Programming with Python - Adv.
Programming with Python - Adv.Programming with Python - Adv.
Programming with Python - Adv.
 
Do...while loop structure
Do...while loop structureDo...while loop structure
Do...while loop structure
 
Thrfit从入门到精通
Thrfit从入门到精通Thrfit从入门到精通
Thrfit从入门到精通
 
Loops in c
Loops in cLoops in c
Loops in c
 
Applied cryptanalysis - everything else
Applied cryptanalysis - everything elseApplied cryptanalysis - everything else
Applied cryptanalysis - everything else
 
TypeScript, Now.
TypeScript, Now.TypeScript, Now.
TypeScript, Now.
 
Looping statement
Looping statementLooping statement
Looping statement
 
Switch case and looping
Switch case and loopingSwitch case and looping
Switch case and looping
 
MATLAB Programming - Loop Control Part 2
MATLAB Programming - Loop Control Part 2MATLAB Programming - Loop Control Part 2
MATLAB Programming - Loop Control Part 2
 

Similar to PHP floating point precision

Microcontroladores: Programación en C para microcontroladores con AVR Butterf...
Microcontroladores: Programación en C para microcontroladores con AVR Butterf...Microcontroladores: Programación en C para microcontroladores con AVR Butterf...
Microcontroladores: Programación en C para microcontroladores con AVR Butterf...
SANTIAGO PABLO ALBERTO
 
Simplifying training deep and serving learning models with big data in python...
Simplifying training deep and serving learning models with big data in python...Simplifying training deep and serving learning models with big data in python...
Simplifying training deep and serving learning models with big data in python...
Holden Karau
 
CPAP.com Introduction To Coding: Part 2
CPAP.com Introduction To Coding: Part 2CPAP.com Introduction To Coding: Part 2
CPAP.com Introduction To Coding: Part 2johnnygoodman
 
Programming in PHP Course Material BCA 6th Semester
Programming in PHP Course Material BCA 6th SemesterProgramming in PHP Course Material BCA 6th Semester
Programming in PHP Course Material BCA 6th Semester
SanthiNivas
 
An SEO’s Intro to Web Dev PHP
An SEO’s Intro to Web Dev PHPAn SEO’s Intro to Web Dev PHP
An SEO’s Intro to Web Dev PHP
Troyfawkes
 
Kaggle Tweet Sentiment Extraction: 1st place solution
Kaggle Tweet Sentiment Extraction: 1st place solutionKaggle Tweet Sentiment Extraction: 1st place solution
Kaggle Tweet Sentiment Extraction: 1st place solution
ArtsemZhyvalkouski
 
Php operators
Php operatorsPhp operators
Php operators
Aashiq Kuchey
 
Php web development
Php web developmentPhp web development
Php web development
Ramesh Gupta
 
Powering Tensorflow with big data using Apache Beam, Flink, and Spark - OSCON...
Powering Tensorflow with big data using Apache Beam, Flink, and Spark - OSCON...Powering Tensorflow with big data using Apache Beam, Flink, and Spark - OSCON...
Powering Tensorflow with big data using Apache Beam, Flink, and Spark - OSCON...
Holden Karau
 
Nullcon Hack IM 2011 walk through
Nullcon Hack IM 2011 walk throughNullcon Hack IM 2011 walk through
Nullcon Hack IM 2011 walk through
Anant Shrivastava
 
PHP MATERIAL
PHP MATERIALPHP MATERIAL
PHP MATERIAL
zatax
 
Php, mysq lpart1
Php, mysq lpart1Php, mysq lpart1
Php, mysq lpart1
Subhasis Nayak
 
Introduction to Python Part-1
Introduction to Python Part-1Introduction to Python Part-1
Introduction to Python Part-1
Devashish Kumar
 
What Is Php
What Is PhpWhat Is Php
What Is Php
AVC
 
PHP - Web Development
PHP - Web DevelopmentPHP - Web Development
PHP - Web Development
Niladri Karmakar
 
Going loopy - Introduction to Loops.pptx
Going loopy - Introduction to Loops.pptxGoing loopy - Introduction to Loops.pptx
Going loopy - Introduction to Loops.pptx
Amy Nightingale
 

Similar to PHP floating point precision (20)

Doc
DocDoc
Doc
 
Microcontroladores: Programación en C para microcontroladores con AVR Butterf...
Microcontroladores: Programación en C para microcontroladores con AVR Butterf...Microcontroladores: Programación en C para microcontroladores con AVR Butterf...
Microcontroladores: Programación en C para microcontroladores con AVR Butterf...
 
Simplifying training deep and serving learning models with big data in python...
Simplifying training deep and serving learning models with big data in python...Simplifying training deep and serving learning models with big data in python...
Simplifying training deep and serving learning models with big data in python...
 
CPAP.com Introduction To Coding: Part 2
CPAP.com Introduction To Coding: Part 2CPAP.com Introduction To Coding: Part 2
CPAP.com Introduction To Coding: Part 2
 
Programming in PHP Course Material BCA 6th Semester
Programming in PHP Course Material BCA 6th SemesterProgramming in PHP Course Material BCA 6th Semester
Programming in PHP Course Material BCA 6th Semester
 
PHP
PHPPHP
PHP
 
An SEO’s Intro to Web Dev PHP
An SEO’s Intro to Web Dev PHPAn SEO’s Intro to Web Dev PHP
An SEO’s Intro to Web Dev PHP
 
Kaggle Tweet Sentiment Extraction: 1st place solution
Kaggle Tweet Sentiment Extraction: 1st place solutionKaggle Tweet Sentiment Extraction: 1st place solution
Kaggle Tweet Sentiment Extraction: 1st place solution
 
Php operators
Php operatorsPhp operators
Php operators
 
Php web development
Php web developmentPhp web development
Php web development
 
Powering Tensorflow with big data using Apache Beam, Flink, and Spark - OSCON...
Powering Tensorflow with big data using Apache Beam, Flink, and Spark - OSCON...Powering Tensorflow with big data using Apache Beam, Flink, and Spark - OSCON...
Powering Tensorflow with big data using Apache Beam, Flink, and Spark - OSCON...
 
Lesson 3 php numbers
Lesson 3  php numbersLesson 3  php numbers
Lesson 3 php numbers
 
Nullcon Hack IM 2011 walk through
Nullcon Hack IM 2011 walk throughNullcon Hack IM 2011 walk through
Nullcon Hack IM 2011 walk through
 
PHP MATERIAL
PHP MATERIALPHP MATERIAL
PHP MATERIAL
 
Php, mysq lpart1
Php, mysq lpart1Php, mysq lpart1
Php, mysq lpart1
 
Introduction to Python Part-1
Introduction to Python Part-1Introduction to Python Part-1
Introduction to Python Part-1
 
What Is Php
What Is PhpWhat Is Php
What Is Php
 
PHP - Web Development
PHP - Web DevelopmentPHP - Web Development
PHP - Web Development
 
Going loopy - Introduction to Loops.pptx
Going loopy - Introduction to Loops.pptxGoing loopy - Introduction to Loops.pptx
Going loopy - Introduction to Loops.pptx
 
Cs3430 lecture 15
Cs3430 lecture 15Cs3430 lecture 15
Cs3430 lecture 15
 

More from Daniel_Rhodes

PhoneGap by Dissection
PhoneGap by DissectionPhoneGap by Dissection
PhoneGap by Dissection
Daniel_Rhodes
 
Hyperlocalisation or "localising everything"
Hyperlocalisation or "localising everything"Hyperlocalisation or "localising everything"
Hyperlocalisation or "localising everything"
Daniel_Rhodes
 
Creating a constructive comment culture
Creating a constructive comment cultureCreating a constructive comment culture
Creating a constructive comment culture
Daniel_Rhodes
 
"Internationalisation with PHP and Intl" source code
"Internationalisation with PHP and Intl" source code"Internationalisation with PHP and Intl" source code
"Internationalisation with PHP and Intl" source code
Daniel_Rhodes
 
Internationalisation with PHP and Intl
Internationalisation with PHP and IntlInternationalisation with PHP and Intl
Internationalisation with PHP and Intl
Daniel_Rhodes
 
Character sets and iconv
Character sets and iconvCharacter sets and iconv
Character sets and iconv
Daniel_Rhodes
 
"Character sets and iconv" PHP source code
"Character sets and iconv" PHP source code"Character sets and iconv" PHP source code
"Character sets and iconv" PHP source code
Daniel_Rhodes
 
Handling multibyte CSV files in PHP
Handling multibyte CSV files in PHPHandling multibyte CSV files in PHP
Handling multibyte CSV files in PHP
Daniel_Rhodes
 
Multibyte string handling in PHP
Multibyte string handling in PHPMultibyte string handling in PHP
Multibyte string handling in PHP
Daniel_Rhodes
 

More from Daniel_Rhodes (9)

PhoneGap by Dissection
PhoneGap by DissectionPhoneGap by Dissection
PhoneGap by Dissection
 
Hyperlocalisation or "localising everything"
Hyperlocalisation or "localising everything"Hyperlocalisation or "localising everything"
Hyperlocalisation or "localising everything"
 
Creating a constructive comment culture
Creating a constructive comment cultureCreating a constructive comment culture
Creating a constructive comment culture
 
"Internationalisation with PHP and Intl" source code
"Internationalisation with PHP and Intl" source code"Internationalisation with PHP and Intl" source code
"Internationalisation with PHP and Intl" source code
 
Internationalisation with PHP and Intl
Internationalisation with PHP and IntlInternationalisation with PHP and Intl
Internationalisation with PHP and Intl
 
Character sets and iconv
Character sets and iconvCharacter sets and iconv
Character sets and iconv
 
"Character sets and iconv" PHP source code
"Character sets and iconv" PHP source code"Character sets and iconv" PHP source code
"Character sets and iconv" PHP source code
 
Handling multibyte CSV files in PHP
Handling multibyte CSV files in PHPHandling multibyte CSV files in PHP
Handling multibyte CSV files in PHP
 
Multibyte string handling in PHP
Multibyte string handling in PHPMultibyte string handling in PHP
Multibyte string handling in PHP
 

Recently uploaded

DevOps and Testing slides at DASA Connect
DevOps and Testing slides at DASA ConnectDevOps and Testing slides at DASA Connect
DevOps and Testing slides at DASA Connect
Kari Kakkonen
 
LF Energy Webinar: Electrical Grid Modelling and Simulation Through PowSyBl -...
LF Energy Webinar: Electrical Grid Modelling and Simulation Through PowSyBl -...LF Energy Webinar: Electrical Grid Modelling and Simulation Through PowSyBl -...
LF Energy Webinar: Electrical Grid Modelling and Simulation Through PowSyBl -...
DanBrown980551
 
20240605 QFM017 Machine Intelligence Reading List May 2024
20240605 QFM017 Machine Intelligence Reading List May 202420240605 QFM017 Machine Intelligence Reading List May 2024
20240605 QFM017 Machine Intelligence Reading List May 2024
Matthew Sinclair
 
GraphSummit Singapore | Enhancing Changi Airport Group's Passenger Experience...
GraphSummit Singapore | Enhancing Changi Airport Group's Passenger Experience...GraphSummit Singapore | Enhancing Changi Airport Group's Passenger Experience...
GraphSummit Singapore | Enhancing Changi Airport Group's Passenger Experience...
Neo4j
 
UiPath Test Automation using UiPath Test Suite series, part 5
UiPath Test Automation using UiPath Test Suite series, part 5UiPath Test Automation using UiPath Test Suite series, part 5
UiPath Test Automation using UiPath Test Suite series, part 5
DianaGray10
 
FIDO Alliance Osaka Seminar: Passkeys at Amazon.pdf
FIDO Alliance Osaka Seminar: Passkeys at Amazon.pdfFIDO Alliance Osaka Seminar: Passkeys at Amazon.pdf
FIDO Alliance Osaka Seminar: Passkeys at Amazon.pdf
FIDO Alliance
 
Microsoft - Power Platform_G.Aspiotis.pdf
Microsoft - Power Platform_G.Aspiotis.pdfMicrosoft - Power Platform_G.Aspiotis.pdf
Microsoft - Power Platform_G.Aspiotis.pdf
Uni Systems S.M.S.A.
 
Secstrike : Reverse Engineering & Pwnable tools for CTF.pptx
Secstrike : Reverse Engineering & Pwnable tools for CTF.pptxSecstrike : Reverse Engineering & Pwnable tools for CTF.pptx
Secstrike : Reverse Engineering & Pwnable tools for CTF.pptx
nkrafacyberclub
 
Removing Uninteresting Bytes in Software Fuzzing
Removing Uninteresting Bytes in Software FuzzingRemoving Uninteresting Bytes in Software Fuzzing
Removing Uninteresting Bytes in Software Fuzzing
Aftab Hussain
 
Elizabeth Buie - Older adults: Are we really designing for our future selves?
Elizabeth Buie - Older adults: Are we really designing for our future selves?Elizabeth Buie - Older adults: Are we really designing for our future selves?
Elizabeth Buie - Older adults: Are we really designing for our future selves?
Nexer Digital
 
Why You Should Replace Windows 11 with Nitrux Linux 3.5.0 for enhanced perfor...
Why You Should Replace Windows 11 with Nitrux Linux 3.5.0 for enhanced perfor...Why You Should Replace Windows 11 with Nitrux Linux 3.5.0 for enhanced perfor...
Why You Should Replace Windows 11 with Nitrux Linux 3.5.0 for enhanced perfor...
SOFTTECHHUB
 
PHP Frameworks: I want to break free (IPC Berlin 2024)
PHP Frameworks: I want to break free (IPC Berlin 2024)PHP Frameworks: I want to break free (IPC Berlin 2024)
PHP Frameworks: I want to break free (IPC Berlin 2024)
Ralf Eggert
 
GraphSummit Singapore | The Art of the Possible with Graph - Q2 2024
GraphSummit Singapore | The Art of the  Possible with Graph - Q2 2024GraphSummit Singapore | The Art of the  Possible with Graph - Q2 2024
GraphSummit Singapore | The Art of the Possible with Graph - Q2 2024
Neo4j
 
PCI PIN Basics Webinar from the Controlcase Team
PCI PIN Basics Webinar from the Controlcase TeamPCI PIN Basics Webinar from the Controlcase Team
PCI PIN Basics Webinar from the Controlcase Team
ControlCase
 
Communications Mining Series - Zero to Hero - Session 1
Communications Mining Series - Zero to Hero - Session 1Communications Mining Series - Zero to Hero - Session 1
Communications Mining Series - Zero to Hero - Session 1
DianaGray10
 
Encryption in Microsoft 365 - ExpertsLive Netherlands 2024
Encryption in Microsoft 365 - ExpertsLive Netherlands 2024Encryption in Microsoft 365 - ExpertsLive Netherlands 2024
Encryption in Microsoft 365 - ExpertsLive Netherlands 2024
Albert Hoitingh
 
FIDO Alliance Osaka Seminar: Passkeys and the Road Ahead.pdf
FIDO Alliance Osaka Seminar: Passkeys and the Road Ahead.pdfFIDO Alliance Osaka Seminar: Passkeys and the Road Ahead.pdf
FIDO Alliance Osaka Seminar: Passkeys and the Road Ahead.pdf
FIDO Alliance
 
FIDO Alliance Osaka Seminar: FIDO Security Aspects.pdf
FIDO Alliance Osaka Seminar: FIDO Security Aspects.pdfFIDO Alliance Osaka Seminar: FIDO Security Aspects.pdf
FIDO Alliance Osaka Seminar: FIDO Security Aspects.pdf
FIDO Alliance
 
Video Streaming: Then, Now, and in the Future
Video Streaming: Then, Now, and in the FutureVideo Streaming: Then, Now, and in the Future
Video Streaming: Then, Now, and in the Future
Alpen-Adria-Universität
 
Uni Systems Copilot event_05062024_C.Vlachos.pdf
Uni Systems Copilot event_05062024_C.Vlachos.pdfUni Systems Copilot event_05062024_C.Vlachos.pdf
Uni Systems Copilot event_05062024_C.Vlachos.pdf
Uni Systems S.M.S.A.
 

Recently uploaded (20)

DevOps and Testing slides at DASA Connect
DevOps and Testing slides at DASA ConnectDevOps and Testing slides at DASA Connect
DevOps and Testing slides at DASA Connect
 
LF Energy Webinar: Electrical Grid Modelling and Simulation Through PowSyBl -...
LF Energy Webinar: Electrical Grid Modelling and Simulation Through PowSyBl -...LF Energy Webinar: Electrical Grid Modelling and Simulation Through PowSyBl -...
LF Energy Webinar: Electrical Grid Modelling and Simulation Through PowSyBl -...
 
20240605 QFM017 Machine Intelligence Reading List May 2024
20240605 QFM017 Machine Intelligence Reading List May 202420240605 QFM017 Machine Intelligence Reading List May 2024
20240605 QFM017 Machine Intelligence Reading List May 2024
 
GraphSummit Singapore | Enhancing Changi Airport Group's Passenger Experience...
GraphSummit Singapore | Enhancing Changi Airport Group's Passenger Experience...GraphSummit Singapore | Enhancing Changi Airport Group's Passenger Experience...
GraphSummit Singapore | Enhancing Changi Airport Group's Passenger Experience...
 
UiPath Test Automation using UiPath Test Suite series, part 5
UiPath Test Automation using UiPath Test Suite series, part 5UiPath Test Automation using UiPath Test Suite series, part 5
UiPath Test Automation using UiPath Test Suite series, part 5
 
FIDO Alliance Osaka Seminar: Passkeys at Amazon.pdf
FIDO Alliance Osaka Seminar: Passkeys at Amazon.pdfFIDO Alliance Osaka Seminar: Passkeys at Amazon.pdf
FIDO Alliance Osaka Seminar: Passkeys at Amazon.pdf
 
Microsoft - Power Platform_G.Aspiotis.pdf
Microsoft - Power Platform_G.Aspiotis.pdfMicrosoft - Power Platform_G.Aspiotis.pdf
Microsoft - Power Platform_G.Aspiotis.pdf
 
Secstrike : Reverse Engineering & Pwnable tools for CTF.pptx
Secstrike : Reverse Engineering & Pwnable tools for CTF.pptxSecstrike : Reverse Engineering & Pwnable tools for CTF.pptx
Secstrike : Reverse Engineering & Pwnable tools for CTF.pptx
 
Removing Uninteresting Bytes in Software Fuzzing
Removing Uninteresting Bytes in Software FuzzingRemoving Uninteresting Bytes in Software Fuzzing
Removing Uninteresting Bytes in Software Fuzzing
 
Elizabeth Buie - Older adults: Are we really designing for our future selves?
Elizabeth Buie - Older adults: Are we really designing for our future selves?Elizabeth Buie - Older adults: Are we really designing for our future selves?
Elizabeth Buie - Older adults: Are we really designing for our future selves?
 
Why You Should Replace Windows 11 with Nitrux Linux 3.5.0 for enhanced perfor...
Why You Should Replace Windows 11 with Nitrux Linux 3.5.0 for enhanced perfor...Why You Should Replace Windows 11 with Nitrux Linux 3.5.0 for enhanced perfor...
Why You Should Replace Windows 11 with Nitrux Linux 3.5.0 for enhanced perfor...
 
PHP Frameworks: I want to break free (IPC Berlin 2024)
PHP Frameworks: I want to break free (IPC Berlin 2024)PHP Frameworks: I want to break free (IPC Berlin 2024)
PHP Frameworks: I want to break free (IPC Berlin 2024)
 
GraphSummit Singapore | The Art of the Possible with Graph - Q2 2024
GraphSummit Singapore | The Art of the  Possible with Graph - Q2 2024GraphSummit Singapore | The Art of the  Possible with Graph - Q2 2024
GraphSummit Singapore | The Art of the Possible with Graph - Q2 2024
 
PCI PIN Basics Webinar from the Controlcase Team
PCI PIN Basics Webinar from the Controlcase TeamPCI PIN Basics Webinar from the Controlcase Team
PCI PIN Basics Webinar from the Controlcase Team
 
Communications Mining Series - Zero to Hero - Session 1
Communications Mining Series - Zero to Hero - Session 1Communications Mining Series - Zero to Hero - Session 1
Communications Mining Series - Zero to Hero - Session 1
 
Encryption in Microsoft 365 - ExpertsLive Netherlands 2024
Encryption in Microsoft 365 - ExpertsLive Netherlands 2024Encryption in Microsoft 365 - ExpertsLive Netherlands 2024
Encryption in Microsoft 365 - ExpertsLive Netherlands 2024
 
FIDO Alliance Osaka Seminar: Passkeys and the Road Ahead.pdf
FIDO Alliance Osaka Seminar: Passkeys and the Road Ahead.pdfFIDO Alliance Osaka Seminar: Passkeys and the Road Ahead.pdf
FIDO Alliance Osaka Seminar: Passkeys and the Road Ahead.pdf
 
FIDO Alliance Osaka Seminar: FIDO Security Aspects.pdf
FIDO Alliance Osaka Seminar: FIDO Security Aspects.pdfFIDO Alliance Osaka Seminar: FIDO Security Aspects.pdf
FIDO Alliance Osaka Seminar: FIDO Security Aspects.pdf
 
Video Streaming: Then, Now, and in the Future
Video Streaming: Then, Now, and in the FutureVideo Streaming: Then, Now, and in the Future
Video Streaming: Then, Now, and in the Future
 
Uni Systems Copilot event_05062024_C.Vlachos.pdf
Uni Systems Copilot event_05062024_C.Vlachos.pdfUni Systems Copilot event_05062024_C.Vlachos.pdf
Uni Systems Copilot event_05062024_C.Vlachos.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 ●