Originally published on php2rust.dev — part of the PHP to Rust course. View this lesson on the original site.
Rust has two floating-point types: f32 and f64. PHP has a single float type (double precision).
Rust
fn main() {
let x: f64 = 3.14; // Default, double precision
let y: f32 = 2.5_f32; // Single precision
let sum = x + y as f64; // Must convert for mixed operations
println!("sum = {}", sum);
// Special values
let inf = f64::INFINITY;
let nan = f64::NAN;
println!("inf = {}, nan = {}", inf, nan);
}
f64is the default (likedoublein C).f32uses less memory,f64is more precise.- Mixed arithmetic requires explicit conversion.
PHP
<?php
$x = 3.14; // float (double precision)
$y = 2.5;
$sum = $x + $y;
echo "sum = $sum\n";
// PHP has is_finite(), is_infinite(), is_nan()
$inf = INF;
$nan = NAN;
var_dump(is_infinite($inf)); // true
var_dump(is_nan($nan)); // true
PHP uses 64-bit floats (IEEE 754 double). There is no single-precision type.
Comparison
- Rust: f32 and f64; default is f64. Use suffix for literals:
2.0_f32. - PHP: Single
floattype (double precision).
References
What's next
Next: Booleans.
From PHP to Rust — Rust Syntax and Functions