简体   繁体   English

移动逗号 position JavaScript

[英]Move comma position JavaScript

I'm trying to move the position of the comma with the use of JavaScript. I have managed to remove all the parts of the string I needed removing.我正在尝试使用 JavaScript 移动逗号的 position。我设法删除了我需要删除的字符串的所有部分。 The only problem is that the comma is in the wrong position.唯一的问题是逗号写错了position。

The current outcome is 425.00 , but I simply want '42.50'当前结果是425.00 ,但我只想要 '42.50'

success: function(result) {
   if (result != '') {
      alert(" "+result+" ");
   }

   var discountVal = result.replace(/\D/g,'');
   newDiscountVal = discountVal.replace(7.50, '');
   $("input#amount").val(discountVal);
}

I am grabbing database echo values with a combination of string and echo - numbers..我正在使用字符串和回声数字的组合来获取数据库回声值。

If it is number you can just divide by 10如果是数字,你可以除以 10

If it is string you can do like this:如果它是字符串,你可以这样做:

var ind = text.indexOf('.');
text = text.replace('.', '');
text.slice(0, ind-1) + '.' + text.slice(ind-1, text.length)

You could divide by ten, then convert back to a String using toFixed(2) which forces formatting of 2 decimal places您可以除以 10,然后使用 toFixed(2) 转换回字符串,这会强制格式化为 2 个小数位

Javascript allows implicit conversion of Strings to numbers, by firstly converting the String to a Number so it is valid to divide a String by a number. Javascript 允许将字符串隐式转换为数字,首先将字符串转换为数字,因此将字符串除以数字是有效的。

var input= "4250.00";
var output = (original / 100).toFixed(2); // => "42.50" 

Note this method has different behaviour due to rounding.请注意,由于四舍五入,此方法具有不同的行为。 Consider the case 9.99.考虑案例 9.99。 If you use a string manipulation technique you'll get ".99", with divide by 10 method above you'll get "1.00".如果您使用字符串操作技术,您将获得“.99”,使用上述除以 10 的方法,您将获得“1.00”。 However from what has been said in comments I believe your inputs always end .00 and never anything else, so there will be no difference in reality.但是,从评论中所说的内容来看,我相信您的输入总是以 .00 结尾,而不会以其他任何内容结尾,因此在现实中不会有任何区别。

Here is a solution:这是一个解决方案:

function moveComma(val, moveCommaByInput) {
  if (val || typeof val === 'number') {
    const valueNumber = Number(val);
    const moveCommaBy = moveCommaByInput || 0;

    if (isNaN(valueNumber)) {
      return null;
    } else {
      return Number(`${valueNumber}e${moveCommaBy}`);
    }
  }

  return null;
}

This is how i solved it..我就是这样解决的..

                      var discountVal = result.replace(/\D/g, '');
                      var newDiscountVal = discountVal.replace(7.50, '');
                      var lastDigits = newDiscountVal.substr(newDiscountVal.length - 2);
                      var removedDigits = newDiscountVal.slice(0,newDiscountVal.length - 2);
                      var discountRealValue = removedDigits + '.' + lastDigits;
                      $("input#amount").val(discountRealValue);

Cheers干杯

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

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