MikeMcl / bignumber.js

A JavaScript library for arbitrary-precision decimal and non-decimal arithmetic
http://mikemcl.github.io/bignumber.js
MIT License
6.64k stars 741 forks source link

How to keep safety when convert '*' to BigNumber #301

Closed Sapphire2k closed 2 years ago

Sapphire2k commented 2 years ago

My project is filled with BigNumber(Number).times(), something like that to a series of calculate, , too many to format a number before to BigNumber(), is that anywhere to config special value as a normal output?

for a example:

var total = '***'
var num = 2
var price = BigNumber(total).div(num).toFixed(2) //  Error total  NaN

What i expected:

var price = BigNumber(total).div(num).toFixed(2) //  ***

just output the origin value without interupt the process T.T

What's more, can we change or redefined BigNumber() constructor or isNaN(), so i can add code to avoid the error.

Thx

MikeMcl commented 2 years ago

There is no "Error" in your example, the variable "price" just becomes BigNumber NaN.

And what "interupt the process" are you referring to?

Frankly, it seems absurd to want to be able to create a BigNumber with the value '***' and I am not inclined to spend any time considering how to do it.

shuckster commented 2 years ago

I think he might be asking for something like this:

var total = '***'
var num = 2
var price = BigNumber(total).div(num).toFixed(2)

if (isNaN(price)) {
  price = total
}

// price === "***"

Is that right @Sapphire2k ?

You can also make a function to help you too:

function Either({ left, right }) {
  return !isNaN(left) ? left : right
}

var total = '***'
var num = 2
var price = Either({
  left: BigNumber(total).div(num).toFixed(2),
  right: total,
})

// price === "***"
Sapphire2k commented 2 years ago

There is no "Error" in your example, the variable "price" just becomes BigNumber NaN.

And what "interupt the process" are you referring to?

Frankly, it seems absurd to want to be able to create a BigNumber with the value '***' and I am not inclined to spend any time considering how to do it.

Thanks for answering, @MikeMcl Oops, My bad. It's no error in my example, what i had used to Big.js. Actually, in my financial project, someone has no auth to check the price or the total amount, when it try to calculate, i get 'NaN' to submit T......T, but '***' for the server is allowed to show his auth.

But now, i can not fastly, completely to instead of all of them or cover it, as @shuckster (Thanks Bro) said to do..

MikeMcl commented 2 years ago
var price = BigNumber(total).div(num);
if (price.isNaN()) {
// etc.