¿Cómo analizar float con dos decimales en javascript?


Tengo el siguiente código. Me gustaría tener tal que si price_result es igual a un entero, digamos 10, entonces me gustaría añadir dos decimales. Así que 10 sería 10.00. O si es igual a 10.6 sería 10.60. No estoy seguro de cómo hacer esto.

price_result = parseFloat(test_var.split('$')[1].slice(0,-1));
Author: Ramratan Gupta, 2010-12-14

12 answers

Puedes usar toFixed () para hacer eso

var twoPlacedFloat = parseFloat(yourString).toFixed(2)
 756
Author: Mahesh Velaga,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2013-03-11 16:09:02

Cuando se usa toFixed, siempre devuelve el valor como una cadena. Esto a veces complica el código. Para evitar eso, puede hacer un método alternativo para el número.

Number.prototype.round = function(p) {
  p = p || 10;
  return parseFloat( this.toFixed(p) );
};

Y uso:

var n = 22 / 7; // 3.142857142857143
n.round(3); // 3.143

O simplemente:

(22/7).round(3); // 3.143
 40
Author: Vlada,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2015-07-15 19:07:00

Si necesitas rendimiento (como en los juegos):

Math.round(number * 100) / 100

Es aproximadamente 100 veces más rápido que parseFloat (número.toFixed (2))

Http://jsperf.com/parsefloat-tofixed-vs-math-round

 34
Author: Rob Boerman,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2015-02-14 11:54:44

Para devolver un número, agregue otra capa de paréntesis. Lo mantiene limpio.

var twoPlacedFloat = parseFloat((10.02745).toFixed(2));
 6
Author: pvanallen,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2015-04-09 19:24:34

Si tu objetivo es analizar, y tu entrada podría ser literal, entonces esperarías que float y toFixed no proporcionaran eso, así que aquí hay dos funciones simples para proporcionar esto:

function parseFloat2Decimals(value) {
    return parseFloat(parseFloat(value).toFixed(2));
}

function parseFloat2Decimals(value,decimalPlaces) {
    return parseFloat(parseFloat(value).toFixed(decimalPlaces));
}
 1
Author: Savage,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-11-17 09:54:26

Ceil de lodash es probablemente el mejor

_.ceil("315.9250488",2) 
_.ceil(315.9250488,2) 
_.ceil(undefined,2)
_.ceil(null,2)
_.ceil("",2)

Funcionará también con un número y es seguro

 1
Author: Antonio Terreno,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2018-04-27 08:36:11

Prueba esto (ver comentarios en el código):

function fixInteger(el) {
    // this is element's value selector, you should use your own
    value = $(el).val();
    if (value == '') {
        value = 0;
    }
    newValue = parseInt(value);
    // if new value is Nan (when input is a string with no integers in it)
    if (isNaN(newValue)) {
        value = 0;
        newValue = parseInt(value);
    }
    // apply new value to element
    $(el).val(newValue);
}

function fixPrice(el) {
    // this is element's value selector, you should use your own
    value = $(el).val();
    if (value == '') {
        value = 0;
    }
    newValue = parseFloat(value.replace(',', '.')).toFixed(2);
    // if new value is Nan (when input is a string with no integers in it)
    if (isNaN(newValue)) {
        value = 0;
        newValue = parseFloat(value).toFixed(2);
    }
    // apply new value to element
    $(el).val(newValue);
}
 0
Author: Mitre Slavchev,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2014-07-23 10:40:25

Por favor, utilice la siguiente función si no desea redondear.

function ConvertToDecimal(num) {
    num = num.toString(); //If it's not already a String
    num = num.slice(0, (num.indexOf(".")) + 3); //With 3 exposing the hundredths place
   alert('M : ' +  Number(num)); //If you need it back as a Number    
}
 0
Author: Nimesh,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2016-04-19 09:29:32

Para lo que vale: Un número decimal, es un número decimal, o lo redondea a algún otro valor o no. Internamente, se aproximará a una fracción decimal de acuerdo con la regla de artmética y manejo de coma flotante. Se mantiene un número decimal (coma flotante, en JS un doble) internamente, no importa con cuántos dígitos desee mostrarlo.

Para presentarlo para su visualización, puede elegir la precisión de la visualización para lo que desee mediante la conversión de cadenas. Representación es un problema de visualización, no una cosa de almacenamiento.

 0
Author: andora,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2016-08-08 10:37:15

La solución que funciona para mí es la siguiente

parseFloat(value)
 0
Author: Jorge Santos Neill,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2018-09-11 18:00:50

Cadena javascript simple para flotar

var it_price = chief_double($("#ContentPlaceHolder1_txt_it_price").val());

function chief_double(num){
    var n = parseFloat(num);
    if (isNaN(n)) {
        return "0";
    }
    else {
        return parseFloat(num);
    }
}
 -1
Author: Arun Prasad E S,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2016-01-02 05:26:37

Tengo otra solución.

Puedes usar round() para hacer eso en su lugar toFixed()

var twoPlacedFloat = parseFloat(yourString).round(2)
 -2
Author: equipo_INSA-Inditex_OU,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2012-08-20 18:06:00