Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

370
Views
How do you set precision of decimal when there is an "E" involved within the number?

I want to trim my decimal into something like 8.063 instead of the original which is 8.0638304611694E-9. I have implemented a function for it but it doesn't work when there is E-9 in it. Which part should I modify??

public function setPrecision($number, $decimals = 0)
{
    $negation = ($number < 0) ? (-1) : 1;
    $coefficient = 10 ** $decimals;
    return $negation * floor((string)(abs($number) * $coefficient)) / $coefficient;
}

EDIT

The current implementation gave me 0 when I try to call the function.

setPrecision(8.0638304611694E-9, 3); // 0
over 4 years ago · Santiago Trujillo
2 answers
Answer question

0

In PHP, there are (at the moment of writing) 8519 builtin functions. One of them probably does the trick!

You could use log10() and round() in your function:

function setPrecision($number, $precision = 0)
{
    $exponent = floor(log10($number)) - 1;
    return round($number, -$exponent + $precision - 1);
}

over 4 years ago · Santiago Trujillo Report

0

Relative rounding with a certain number of digits can easily be done with sprintf.

$round = (float)sprintf('%0.3E', 8.0638304611694E-9);
var_dump($round);  //float(8.064E-9)

On this basis I have this function which rounds float values with a certain relative decimal precision.

 /*
  * @return Float-Value with reduced precision
  * @param $floatValue: input (float)
  * @param $overallPrecision: 1..20 (default 10)
  */
  function roundPrecision($floatValue, $overallPrecision = 10)
  {
    $p = min(20,max(0,$overallPrecision-1));
    $f =(float)sprintf('%.'.$p.'e',$floatValue);
    return $f;
  }

example 1

  $float = 0.0000123456789;
  $newFloat = roundPrecision($float,5);
  printf('%0.10f',$newFloat);  //0.0000123460

example 2

  $float = 3456.7891234;
  $newFloat = roundPrecision($float,5);
  printf('%0.10f',$newFloat);  //3456.8000000000
over 4 years ago · Santiago Trujillo Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!