简体   繁体   English

在Javascript中将字符串转换为负浮点数

[英]Converting string into negative float number in Javascript

The negative numeric value I'm getting from the back-end application is formatted according to our internal configuration (UI user profile). 我从后端应用程序获得的负数值是根据我们的内部配置(UI用户配置文件)进行格式化的。 In other words, for value -23.79879 my xml input may be <myNumber>-23.79879</myNumber> or <myNumber>23,79879-</myNumber> or other 换句话说,对于值-23.79879,我的xml输入可能是<myNumber>-23.79879</myNumber><myNumber>23,79879-</myNumber>或其他
and I can't turn the formatting off. 而且我无法关闭格式。
The assumption is that the formats are "standard", normally used for localization. 假定格式是“标准”格式,通常用于本地化。
I'm looking to do something like: 我正在寻找类似的东西:

convertStringToNumber(numberString, formatString, slignPosition)

Not sure what you mean with formatString, but maybe something like this?: 不确定您对formatString的含义,但也许是这样的:

function convertStringToNumber(num){
    num=num.split(',').join('.');
    if(num.indexOf('-') ==num.length-1){
        num='-'+num.substr(0,num.length-1);
    }
    return parseFloat(num) || null;
}



console.log(convertStringToNumber("-23.79879"))
console.log(convertStringToNumber("23,79879-"))

The easiest way to achieve this is to expose the parsing rule from the backend, which obviously knows the format. 实现此目的的最简单方法是从后端公开解析规则,而后者显然知道格式。 This can be done in many ways, but one easy way i am fond of is simply to break down all the moving parts of the format, define properties for each on an object and then expose that object to the parser. 这可以通过多种方式完成,但是我喜欢的一种简单方法就是简单地分解格式的所有移动部分,为对象上的每个部分定义属性,然后将该对象公开给解析器。

The object could look something like this: 该对象可能看起来像这样:

var opts =  {
  thousandsSeparator: ',',
  decimalSeparator: '.',
  negativeSign: '-'
};

Then pass that object into a parsing function like this: 然后将该对象传递给这样的解析函数:

function parseNumber(opts, str) {
      var isNegative = false;
        if(str.indexOf(opts.negativeSign) != -1) {
            isNegative = true;
            str = str.replace(opts.negativeSign,'');
        }
        var parts = str.split(opts.thousandsSeparator).join('').split(opts.decimalSeparator);
        var num = 1 * parts[0];
        var deci = 1 * parts[1];
        if(deci) num += deci /  Math.pow(10,parts[1].length);
        return isNegative ? -1 * num : num;
}

You would then call it like thuis: 然后,您将其称为thuis:

parseNumber(opts,'2,345.234-'); parseNumber(选择采用, '2,345.234-'); //-2345.234 //-2345.234

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM