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

277
Visualizações
How to format a number with exact of decimal number without rounding in javascript?

Let say i have a number

const number = 122.333444555666

i want to write a function that will return the exact decimal's number that i want. For example

formatFunction(number, 5) return 122.33344
formatFunction(number, 7) return 122.3334445
formatFunction(number, 12) return 122.333444555666
formatFunction(number, 15) return 122.333444555666000
formatFunction(number, 20) return 122.33344455566600000000

I tried with toFixed() but i end up with some exception . For ex

12.111222333.toFixed(18) return '12.111222333000000617'

I also try Intl but it always rouned up. Any idea?

about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

When working with floats I like to split at the decimal place and treat both sides as whole numbers. It makes operating on them a bit easier and increases accuracy.

const [wholeNumber, decimals] = num.split(".");

Isolating decimals as a string allows us to quickly compare it to they desired scale, enabling us to determine whether to add or subtract.

if (decimals.length < scale) {
    const diff = scale - decimals.length;
    const trailingZeros = new Array(diff).fill(0).join("");
    decimals += trailingZeros;
}

In the above example we have less decimal places than the desired scale. So we'll create a string of zeros based on the difference to match the scale, then append it to the end of the decimal string.

if (decimals.length > scale) {
   decimals = decimals.substr(0, scale);
}

When the decimals places are greater, we can use substr() to cut up to the desired scale.

return join(wholeNumber, decimals)

Lastly we want to rejoin our two sets of numbers using the helper. Note that to satisfy the trailing zeros the answer is returned as a string. Converting it to a number would omit them.

function formatFunction(number, scale) {
    // if it's a number need to convert to string
    const num = typeof number === 'number' ? number.toString() : number;
    let [wholeNumber, decimals] = num.split(".");

    if (decimals.length < scale) {
        const diff = scale - decimals.length;
        const trailingZeros = new Array(diff).fill(0).join("");
        decimals += trailingZeros;
    } else if (decimals.length > scale) {
        decimals = decimals.substr(0, scale);
    }
    // decimals.length === scale
    return join(wholeNumber, decimals)
}

// helper
function join(wholeNumber, decimals) {
    if (!decimals) return wholeNumber;
    return [wholeNumber, decimals].join(".")
}
const number = 122.333444555666;
console.log(formatFunction(number, 5)) // return 122.33344
console.log(formatFunction(number, 7)) // return 122.3334445
console.log(formatFunction(number, 12)) // return 122.333444555666
console.log(formatFunction(number, 15)) // return 122.333444555666000
console.log(formatFunction(number, 20)) // return 122.33344455566600000000

about 4 years ago · Juan Pablo Isaza 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