Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

369
Visualizações
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 Respostas
Responde à pergunta

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 Relatório

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda