96

这是一个简单的场景。我想在我的网站上显示两个值的减法:

//Value on my websites HTML is: "75,00"
var fullcost = parseFloat($("#fullcost").text()); 

//Value on my websites HTML is: "0,03"
var auctioncost = parseFloat($("#auctioncost").text());

alert(fullcost); //Outputs: 75
alert(auctioncost); //Ouputs: 0

谁能告诉我我做错了什么?

4

11 回答 11

183

这是“设计”。该parseFloat函数将仅考虑字符串的部分,直到 in 达到非 +、-、数字、指数或小数点。一旦它看到逗号,它就会停止查找,只考虑“75”部分。

要解决此问题,请将逗号转换为小数点。

var fullcost = parseFloat($("#fullcost").text().replace(',', '.'));
于 2011-09-27T15:21:07.077 回答
36

javascript 的 parseFloat 不采用语言环境参数。所以你将不得不替换,.

parseFloat('0,04'.replace(/,/, '.')); // 0.04
于 2011-09-27T15:20:58.583 回答
21

parseFloat根据十进制文字的 JavaScript 定义进行解析,而不是您的语言环境的定义。(例如,parseFloat不支持区域设置。) JavaScript.中的小数文字用于小数点。

于 2011-09-27T15:21:18.060 回答
21

为什么不使用全球化?这只是您不使用英语时可能遇到的问题之一:

Globalize.parseFloat('0,04'); // 0.04

stackoverflow上的一些链接可以查看:

于 2013-12-27T17:29:03.797 回答
14

正如@JaredPar 在他的回答中指出的那样使用parseFloat替换

var fullcost = parseFloat($("#fullcost").text().replace(',', '.'));

只需用commaa替换dot将修复,除非它是像1.000.000,00这样的数以千计的数字,否则会给你错误的数字。所以你需要更换comma删除的dots

// Remove all dot's. Replace the comma.
var fullcost = parseFloat($("#fullcost").text().replace(/\./g,'').replace(',', '.'));

通过使用两个替换,您将能够处理数据而不会在输出中收到错误的数字。

于 2014-03-17T12:07:07.880 回答
7

JS 中的数字使用.(句号/句点)字符来表示小数点而不是,(逗号)。

于 2011-09-27T15:20:31.430 回答
7

对于到达这里想知道如何处理可能涉及逗号(,)和句号(.)但可能不知道确切数字格式的问题的任何人 - 这就是我在使用之前更正字符串的方式parseFloat()(借鉴其他答案的想法):

function preformatFloat(float){
   if(!float){
      return '';
   };

   //Index of first comma
   const posC = float.indexOf(',');

   if(posC === -1){
      //No commas found, treat as float
      return float;
   };

   //Index of first full stop
   const posFS = float.indexOf('.');

   if(posFS === -1){
      //Uses commas and not full stops - swap them (e.g. 1,23 --> 1.23)
      return float.replace(/\,/g, '.');
   };

   //Uses both commas and full stops - ensure correct order and remove 1000s separators
   return ((posC < posFS) ? (float.replace(/\,/g,'')) : (float.replace(/\./g,'').replace(',', '.')));
};
// <-- parseFloat(preformatFloat('5.200,75'))
// --> 5200.75

至少,这将允许解析英式/美式和欧式十进制格式(假设字符串包含有效数字)。

于 2020-04-03T20:49:10.003 回答
6

一百万个1,234,567的情况下最好用这个语法替换所有的逗号

var string = "1,234,567";
string = string.replace(/[^\d\.\-]/g, ""); 
var number = parseFloat(string);
console.log(number)

g删除所有逗号的方法。

在此处查看Jsfiddle 演示

于 2018-01-20T21:55:40.107 回答
-1

从我的原籍国来看,货币格式类似于“3.050,89 €”

parseFloat 将点标识为小数分隔符,要添加 2 个值,我们可以这样表示:

parseFloat(element.toString().replace(/\./g,'').replace(',', '.'))
于 2020-04-24T09:35:44.787 回答
-1

就我而言,我已经有一个句点(.)和一个逗号(,),所以对我有用的是带有如下空字符串replace的逗号:(,)

parseFloat('3,000.78'.replace(',', '')) 

这是假设来自现有数据库的数量为 3,000.78。结果是:3000.78没有最初的逗号(,)

于 2020-11-18T13:22:02.903 回答
-2

你做错的是parseFloat()用面向人类的符号表示小数部分的字符串,而只接受与JavaScriptparseFloat()数字文字相对应的标准格式,这些文字与区域无关,始终使用点作为小数分隔符,并且没有千位分隔符。

此外,在所有答案中都使用了这个parseFloat()函数,它接受的正确输入过于慷慨,从而阻止了在大多数情况下检测不正确的输入:

Input      Result
'1Hello'   1
'1 and 2'  1
'1.2+3.4'  1.2
' 25  '    25

为了获得更严格并因此得到更好控制的行为,我建议您实现自己的解析功能。这是我的:

// Parse a decimal fraction with specified thousands
// and group separators:
function /* number */ parse_float
(   /* string */ s      , // string to parse
    /* string */ thousep, // thousands separator, empty string if none
    /* string */ decsep   // decimal separator  , empty string if none
)
{   var /* integer */ whole, frac ; // whole and fractinal parts
    var /* integer */ wnext, fnext; // position of next char after parse
    var /* integer */ fraclen     ; // length of fractional part
    var /* integer */ ofs         ; // offset of the first digit
    var /* boolean */ done        ; // entire string scanned?
    var /* integer */ sign        ; // sign of result
    var /* number  */ res         ; // result
        /* labels  */ end: { whole: {

    // Check parameter types and availability:
    req_param( 's'      , s      , 'string' );
    req_param( 'thousep', thousep, 'string' );
    req_param( 'decsep' , decsep , 'string' );
    
    frac    = 0;
    fraclen = 0;
    res     = NaN;
    // Account for a possible sign:
    switch( s.charAt(0) )
    {   case '-': sign = -1; ofs = 1; break;
        case '+': sign = +1; ofs = 1; break;
        default : sign = +1; ofs = 0; break;
    }

    [done, wnext, whole] = parse_int_ts( s, ofs, thousep );
    if( isNaN( whole )               )           break end;
    if( done                         )           break whole;
    if( s.charAt( wnext ) !== decsep )           break end; 
    
    [done, fnext, frac] = parse_int( s, 0, wnext + 1 );
    if( !done                        )           break end;

    fraclen = fnext - wnext - 1;
    if( fraclen === 0                )           break end;

    } /* whole: */ res = ( whole + frac / Math.pow( 10, fraclen ) ) * sign;
    } /* end:   */ return res;
}

// Require that a value be specified and have the expected type:
function req_param( /* string */ param, /* variant */ val, /* string */ type )
{   var /* string */ errmsg;

    errmsg = ''; if( val === undefined   ) errmsg = 'is undefined';
    else         if( val === null        ) errmsg = 'is null';
    else         if( typeof val !== type ) errmsg = `must of type \`${type}'`;

    if( errmsg !== '' ) // there has been an error
    {   throw new Error(`Parameter \`${param}' ${errmsg}.`);  }
}

// Parse an integer with a specified thousands separator:
function /* object[] */ parse_int_ts
(   /* string    */ s    , // input string
    /* integer   */ start, // start position
    /* character */ sep  , // thousands separator
)
// Returns an array of:
//   0: boolean -- entire string was scanned
//   1: integer -- index of next character to scan
//   2: integer -- resulting inteer 
{   var /* boolean */ full;
    var /* integer */ next;
    var /* integer */ res;
    var /* integer */ len;
    var /* integer */ psep;
    var /* integer */ result;
    
    res     = 0;
    psep    = 0;
    while( true )
    {   result = NaN; // mark an error
        [full, next, res] = parse_int( s, res, start );
        len = next - start;
        if( len === 0  )                 break; // nothing parsed
        if( sep !== '' )
        {   if( psep  >  0 && len !== 3 ) break; // non-first group not 3 digits
            if( psep === 0 && len  >  3 ) break; // first group longer than 3 digits
        }
        result = res; // mark success
        if( s.charAt(next) !== sep )     break;
        if(  full   )                    break;
        start = next;
        psep  = next;
        start = start + 1;
    }
    return [full, next, result];
}

// Parse a compact of digits beginning at position `start' 
// in string `s' as an integer number:
function /* object[]*/ parse_int
(   /* string  */ s   , // input string
    /* integer */ init, // initial value
    /* integer */ start // start position in `s'
)
// Returns an array of:
// 0: boolean -- entire string was scanned
// 1: integer -- index of next character to scan
// 2: integer -- result
{   const /* integer */ ASCII_0 = 48;

    var /* boolean   */ full; // \
    var /* integer   */ next; //  > the return value
    var /* integer   */ res ; // /
    var /* integer   */ n, i; // string length and current position
    var /* integer   */ code; // character code

    n    = s.length;
    full = true;
    next = n;
    res  = init;
    for( i = start; i < n; i += 1 )
    {   code = s.charCodeAt(i);
        if( code < ASCII_0 || code >= ASCII_0 + 10 )
        {   next = i;
            full = false;
            break;
        }
        res = res * 10 + code - ASCII_0;
    }
    if( code === undefined ) res = NaN;
    return [ full, next, res ];
}

parse_float()还有一个用于解析格式数字的测试程序:

function test( /* string */ s )
{   var res;
    res = parse_float( s, ' ', ',' );
    console.log(`${('            ' + `[${s}]`).slice(-12)} => ${res}`);
}

test( ''           );
test( '12'         );
test( '12a'        );
test( '12,'        );
test( '12,345'     );
test( '12 345'     );
test( '123 45'     );
test( '1 234 567'  );
test( '12 345 56'  );
test( '12345'      );
test( '12 435,678' );
test( '+1,2'       );
test( '-2 345'     );

它写道:

          [] => NaN
        [12] => 12
       [12a] => NaN
       [12,] => NaN
    [12,345] => 12.345
    [12 345] => 12345
    [123 45] => NaN
 [1 234 567] => 1234567
 [12 345 56] => NaN
     [12345] => NaN
[12 435,678] => 12435.678
      [+1,2] => 1.2
    [-2 345] => -2345
于 2021-06-24T23:51:50.163 回答