how can i make a floating device have 8 digits?

If you’re looking to truncate your numbers to exactly 8 digits (not counting the decimal point):

function myTrunc( $n ) {
    $first9 = substr( $n, 0, 9 ); // The first 9 chars
    $hasDecimal = ( FALSE !== strpos( $first9, '.' ) ); // Whether it contains a decimal
    $r = substr( $first9, 0, $hasDecimal ? 9 : 8 ); // Get first 8 (or 9 if there is a decimal)
    return trim( $r, '.' ); // Trim any trailing decimal (so 12345678. becomes 12345678)
}

$n1 = 1.234567891011;
$n2 = 12.34567891011;
$n3 = 1234567891011;
$n4 = 1234567.891011;
$n5 = 12345678.91011;
$n6 = 123456789.1011;

echo "$n1 truncates to " . myTrunc( $n1 ) . "\n"; // 1.2345678
echo "$n2 truncates to " . myTrunc( $n2 ) . "\n"; // 12.345678
echo "$n3 truncates to " . myTrunc( $n3 ) . "\n"; // 12345678
echo "$n4 truncates to " . myTrunc( $n4 ) . "\n"; // 1234567.8
echo "$n5 truncates to " . myTrunc( $n5 ) . "\n"; // 12345678
echo "$n6 truncates to " . myTrunc( $n6 ) . "\n"; // 12345678

CLICK HERE to find out more related problems solutions.

Leave a Comment

Your email address will not be published.

Scroll to Top