javascript toFixed()

时间:2017-01-18 10:33:38

标签: javascript tofixed

在许多情况下{j}数学中toFixed()失败导致浮点。

我找到了这个解决方案:

function toFixed(decimalPlaces) {
var factor = Math.pow(10, decimalPlaces || 0);
var v = (Math.round(Math.round(this * factor * 100) / 100) / factor).toString();
if (v.indexOf('.') >= 0) {
    return v + factor.toString().substr(v.length - v.indexOf('.'));
}
return v + '.' + factor.toString().substr(1);
}

和此:

function toFixed(num, fixed) {
var re = new RegExp('^-?\\d+(?:\.\\d{0,' + (fixed || -1) + '})?');
return num.toString().match(re)[0];
}

还有其他方法吗?我必须确定在任何情况下都表现良好。也是在临界案件中。

编辑: https://github.com/MikeMcl/decimal.js @Tschallacka

Number.prototype.toFixed = function(fixed) {
x = new Decimal(Number(this));
return x.toFixed(fixed);
};

1 个答案:

答案 0 :(得分:1)

我建议你使用一个库:

https://github.com/MikeMcl/decimal.js

我在使用财务数据时发现它非常可靠。

使用浮点数总是很困难,但有几种解决方案。 我建议你使用一个维护良好的存在库,这已经让它的宝宝牙齿被淘汰了。

假设您添加了decimal.js,您可以为财务值执行此操作。

@implementation DeveloperAuthenticatedIdentityProvider
/*
 * Use the token method to communicate with your backend to get an
 * identityId and token.
 */

- (AWSTask <NSString*>) token {
    //Write code to call your backend:
    //Pass username/password to backend or some sort of token to authenticate user
    //If successful, from backend call getOpenIdTokenForDeveloperIdentity with logins map 
    //containing "your.provider.name":"enduser.username"
    //Return the identity id and token to client
    //You can use AWSTaskCompletionSource to do this asynchronously

    // Set the identity id and return the token
    self.identityId = response.identityId;
    return [AWSTask taskWithResult:response.token];
}

@end
/**
 * @var input float
 */
function toFixed(input) {
  var dec = new Decimal(input);
  return dec.toFixed(2);
}
console.log("float to fixed 2 decimal places: ",toFixed(200.23546546546));



function toFixed2(decimalPlaces) {
  var dec = new Decimal(1);
  return dec.toFixed(decimalPlaces);
}
console.log("get a fixed num: ",toFixed2(10));

Number.prototype.toFixed = function(fixed) {
x = new Decimal(Number(this));
return x.toFixed(fixed);
};

var num = new Number(10.4458);
console.log("Number to fixed via prototyped method: ",num.toFixed(2));

var x = 44.456
console.log('Number to fixed via inderect number casting:' ,x.toFixed(2));