ASGJim
ASGJim

Reputation: 1

Trouble converting javascript string to number

I have a script assigns a variable using parseFloat as follows:

var vendorCost = parseFloat(vendorSearchresults[0].getValue('vendorcost')).toFixed(2);

I assumed this would make the variable a number. However when I check it with typeof - it reports it as a string. My solution is as follows:

vendorCost = parseFloat(vendorCost);

Which works, however I'm trying to be more efficient when coding and would like to understand why it doesn't make vendorCost a number when assigning it a number? Is there a way I could make the first statement make vendorCost a number without the need for the second statement? Thanks in advance.

Update - just thought I should mention I'm having the exact same issue without using .toFixed -

    var vendorLandedCost = parseFloat(vendorSearchresults[0].getValue('custentity_asg_landed_cost','vendor'));
    vendorLandedCost = parseFloat(vendorLandedCost);

Upvotes: 0

Views: 49

Answers (2)

fernandosavio
fernandosavio

Reputation: 10357

Well, Number.toFixed returns string because it is a data presentation function.

See the docs.

Upvotes: 0

MAK
MAK

Reputation: 26586

The last toFixed() call converts the result of the first parseFloat into a string.

Looks like you need to round the number to two decimal places, which is why you're using the parseFloat call. You can do something like this instead:

vendor_cost = Math.round(parseFloat(vendorSearchresults[0].getValue('vendorcost')) * 100) / 100

Upvotes: 1

Related Questions