to的问题已解决

时间:2018-12-18 13:23:46

标签: javascript

因此,我一直在尝试防止toFixed舍入数字时遇到麻烦,我想要实现的是,对于某个数字,将该数字乘以一个特定的数字,然后返回最后两位而不进行舍入

我已阅读以下主题: javascript - how to prevent toFixed from rounding off decimal numbers

事实上,我已经尝试过圣地亚哥·埃尔南德斯的解决方案。

这是小提琴:demo

示例: 6500 * 0.0002 = 1.3

在这种情况下,结果为1,没有考虑3。

POST /services/portal.asmx HTTP/1.1
Host: test.lensportal.co.za
Content-Type: text/xml; charset=utf-8
Content-Length: length
SOAPAction: "http://www.domain.co.za/GetOrderDefinition"


<?xml version="1.0" encoding="utf-8"?>
<soap:Envelope xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:xsd="http://www.w3.org/2001/XMLSchema" 
xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/">
<soap:Body>
 <GetOrderDefinition xmlns="http://www.domain.co.za">
<orderRef>string</orderRef>
</GetOrderDefinition>
</soap:Body>
</soap:Envelope>

我想这是一部分:

var multiplier = 0.0002;
var num = 500 * multiplier;

var toFixed = function(val, decimals) {
  var arr = ("" + val).split(".")
  if(arr.length === 1) 
    return val
  var int = arr[0],
      dec = arr[1],
      max = dec.length - 1
  return decimals === 0 ? int :
    [int,".",dec.substr(0, decimals > max ? max : decimals)].join("")
}

我尝试过的方法: 我取出了max = dec.length - 1 ,并尝试了10种不同类型的数字(987.77、6600.77等),但是我想知道是否还有另一种类型的解决方案,或者上述代码在某些时候是否会失败一些位数

2 个答案:

答案 0 :(得分:0)

这是我的toFixed替代方案,它不舍入数字,只是根据给定的精度将其截断或加零。对于更长的数字,当精度很高时,它使用JS内置舍入。 该函数适用于我在堆栈中发现的所有有问题的数字。

function toFixedFixed(value, precision = 0) {
    let stringValue = isNaN(+value) ? '0' : String(+value);

    if (stringValue.indexOf('e') > -1 || stringValue === 'Infinity' || stringValue === '-Infinity') {
        throw new Error('To large number to be processed');
    }

    let [ beforePoint, afterPoint ] = stringValue.indexOf('.') > -1 ? stringValue.split('.') : [ stringValue, ''];

    // Force automatic rounding for some long real numbers that ends with 99X, by converting it to string, cutting off last digit, then adding extra nines and casting it on number again
    // e.g. 2.0199999999999996: +('2.019999999999999' + '9999') will give 2.02
    if (stringValue.length >= 17 && afterPoint.length > 2 && +afterPoint.substr(afterPoint.length - 3) > 995) {
        stringValue = String(+(stringValue.substr(0, afterPoint.length - 1) + '9'.repeat(stringValue.split('.').shift().length + 4)));
        [ beforePoint, afterPoint ] = String(stringValue).indexOf('.') > -1 ? stringValue.split('.') : [ stringValue, ''];
    }

    if (precision === 0) {
        return beforePoint;
    } else if (afterPoint.length > precision) {
        return `${beforePoint}.${afterPoint.substr(0, precision)}`;
    } else {
        return `${beforePoint}.${afterPoint}${'0'.repeat(precision - afterPoint.length)}`;
    }
}

答案 1 :(得分:0)

另一种实现方式:添加一个值,以便将四舍五入更改为四舍五入

function toCut ( num, digits )
{
    let x = parseFloat("0.5e-"+digits);
    return ( num < 0 ? num+x : num-x ).toFixed(digits);
}
相关问题