1

So i have a form where the user enters a price for an item in ETHER. I understand the blockchain does not handle floatin point numbers currently, so i am attempting to convert to WEI and store it on the block chain that way.

What im doing is the following

const price =.34 //this should be ether
const weiPrice = web3.toWei(cleanPrice, 'ether');
console.log('weiPrice', weiPrice);

output is weiPrice 340000000000000000, which is correct. I am then passing the variable weiPrice into the truffle-contract promise to create a new item.

   return contractInstance.createItem(
        Number(weiPrice),
        Number(cleanQuantity),
        Number(cleanQuantity), {
          from: account,
        })

Everything appears to work, but when i retrieve the value from the blockchain for this item i am getting the following result.

retrieved item

BigNumber {s: 1, e: 17, c: Array(1)}
c: [3400]
e: 17
s: 1__proto__: Object

I need to convert the price back to ether or wei but i guess i just dont understand whats happening here. Can anyone help me understand?

I tried the suggestions from the first couple of comments, here are the results.

console.log('test', item[0].c.valueOf());

output

test [3400]
 0: 3400
 length: 1
 __proto__: Array(0)


console.log('test2', item[0].c.toNumber());

output

Uncaught (in promise) TypeError: item[0].c.toNumber is not a function
  • The returned item is a BigNumber object. You can convert it with its method valueOf() – Henk Aug 26 '18 at 20:11
  • or .toNumber() – Shawn Tabrizi Aug 26 '18 at 20:18
2

Web3.js uses the BigNumber library since JavaScript does not do a good job handling large numbers correctly.

Take a look at the following examples on how you can recover the value you expect:

var val;
web3.eth.getBalance('0x90b0137bf6ddb130ed8e3f28cc9f929b0b609ed2', function (error, wei) { if (!error) { val = wei } })

val
> Object { s: 1, e: 17, c: (2) […] }

val.valueOf()
> "288295053265996304"

val.toNumber()
> 288295053265996300

val.toString()
> "288295053265996304"
  • awesome. that works perfectly. so in my instance i did. item[0].valueOf() – Rick james Aug 26 '18 at 20:34

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.