JS Function "Object expected At line 2 character 0" - javascript

I'm building a plan file for XMPie Uplan. Javascript functions are allowed, so as I am learning JS, I thought I would take advantage of them. They seem friendlier than the proprietary QLingo functions. I don't think that should matter though, it is just JS. Anyone see a problem with my JS?
function cents(p) {
var monfor = toString(parseFloat(Math.round(p * 100) / 100).toFixed(2));
return monfor.slice(-2);
}
The purpose of this code is to return just the cents in a price.
Here is what is supposed to be going on:
First I make sure the number has two decimal places and convert to a string. Then I slice off the last two digits of my string leaving me with a 2 digit integer as a string which is the number of pennies in my price. This will flow into the cents portion of a price field with the cents in superscript. (I have another function that uses floor to kill the sub dollar part of the price that populates the dollar part of the price.) The error on this function is:
Error: cents: An error occurred while executing the function script.
Description: Object expected At line 2 character 0.
Thanks in advance for any help!

var numToParse = parseFloat(Math.round(p * 100) / 100).toFixed(2);
var monfor = numToParse.toString();
return monfor.slice(-2);
You were using the two string in the wrong way.
As mentioned in the comments, i didnt know this, you dont even need to parse it to string as the toFixed() parses it itself.
var monfor = parseFloat(Math.round(p * 100) / 100).toFixed(2);
return monfor.slice(-2);

Related

Vue JS - Calculator - read output string as value

I'm building a calculator to test out my Vue JS skills. I have the fundamentals working or at least set-up, however if I enter more than one number (e.g. 34) I can't get it to read all numbers (e.g. 34) as a whole value; rather it adds 3 and 4 to the total. The snippet I'm having trouble with is here:
press: function(num) {
if(this.currentNum == 0)
{
this.currentNum = num;
this.output = num.toString();
}
else {
this.output += num.toString();
this.currentNum = this.output.parseInt();
}
},
Here's the whole thing on CodePen for better context - https://codepen.io/ajm90UK/pen/BZgZvV
I think this is more of a JS issue rather than anything specific to Vue but even with parseInt() on the string I'm having no luck. Any suggestions on how I can read the display (output) would be greatly appreciated, I've been at this for hours now!
parseInt() is not a method of the String prototype but rather a built-in function.
Update this line:
this.currentNum = this.output.parseInt();
to this:
this.currentNum = parseInt(this.output);
And it is a good idea to specify the radix in the second parameter - perhaps 10 in most all cases, for decimal numbers:
this.currentNum = parseInt(this.output, 10);
That way, if a value like 022 is entered, it isn't interpreted as the octal value (I.e. Decimal number 18).

How to get an 8 decimal output?

I am trying to get an 8 decimal output from the following function.
The following function multiplies an input by 2 and then updates this input with the wagerUpdate variable. I would like this outputted number to have 8 decimal places.
For example: if input number is 0.00000001 (this code is for a bitcoin website), then I would like output number to be 0.00000002. For some reason the code below is not working properly as the output number is in the format of 2e-8 without the .toFixed(8) code. Please help if you are able to. Thank you so much.
<script>
function MultiplyWagerFunction() {
var wager = document.getElementById("wagerInputBox").value;
var wagerUpdate = wager*2;
document.getElementById("wagerInputBox").value = +wagerUpdate.toFixed(8);
}
</script>
If you remove the + before wagerUpdate.toFixed(8) it should work fine. wagerUpdate has already be converted to a number when you multiplied it by 2 so there should be no need for the unary +
var a = "0.00000001";
var b = a*2;
console.log(b.toFixed(8));
console.log(+b.toFixed(8));
^ see the difference.
The reason it doesn't work is because what you are doing is equivalent to:
+(b.toFixed(8))
because of the precedence of the operators (member access . is higher than unary +). You are converting b to a string with .toFixed and then converting it back into a number with + and then converting it back into a string again! (this time with the default toString behavior for numbers giving you exponential notation)
Just remove + from +wagerUpdate.toFixed(8); and you would be good.
Instead of:
document.getElementById("wagerInputBox").value = +wagerUpdate.toFixed(8);
try:
document.getElementById("wagerInputBox").innerHTML = +wagerUpdate.toFixed(8);
Why I say so is may be when you set value, browser tries to convert to best possible outcome. But, inner HTML should take the string equivalent!

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);
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
Well, Number.toFixed returns string because it is a data presentation function.
See the docs.

Javascript coding a calculation

I'm coding a price calculator in JS and I'm stuck with one formula:
number = (parseFloat(newnumber, 10) * parseFloat(1.536, 10)).toString(10);
I want to add 7.44 to the value of newnumber, before it is multiplied with 1.536
I've tried several things, but with no success.
Going to submit this as an answer, even though someone has put this up a comment while I was typing my answer.
number = ((+newnumber + 7.44) * 1.536).toString();
That should give you a string representation of the summed value.
Use parentheses to make the addition before the multiplication.
number = ((parseFloat(newnumber) + 7.44) * 1.536).toString();
Notes: parseFloat doesn't have a radix parameter. There is no reason to parse the number 1.536, that will only turn it to a string and then back to the same number again. The default for the radix parameter for toString is 10, so that isn't needed.
number = ((parseFloat(newnumber) + 7.44) * parseFloat(1.536)).toString();?
Just use parentheses to separate out the operations. Simple fix.
Working DEMO
Try the following code -
var newnumber = '1';
var number = ((parseFloat(newnumber) + 7.44) * parseFloat(1.536)).toString(10);
alert(number);

Javascript convert string to integer

I am just dipping my toe into the confusing world of javascript, more out of necessity than desire and I have come across a problem of adding two integers.
1,700.00 + 500.00
returns 1,700.00500.00
So after some research I see that 1,700.00 is being treated as a string and that I need to convert it.
The most relevant pages I read to resolve this were this question and this page. However when I use
parseInt(string, radix)
it returns 1. Am I using the wrong function or the an incorrect radix (being honest I can't get my head around how I decide which radix to use).
var a="1,700.00";
var b=500.00;
parseInt(a, 10);
Basic Answer
The reason parseInt is not working is because of the comma. You could remove the comma using a regex such as:
var num = '1,700.00';
num = num.replace(/\,/g,'');
This will return a string with a number in it. Now you can parseInt. If you do not choose a radix it will default to 10 which was the correct value to use here.
num = parseInt(num);
Do this for each of your string numbers before adding them and everything should work.
More information
How the replace works:
More information on replace at mdn:
`/` - start
`\,` - escaped comma
`/` - end
`g` - search globally
The global search will look for all matches (it would stop after the first match without this)
'' replace the matched sections with an empty string, essentially deleting them.
Regular Expressions
A great tool to test regular expressions: Rubular and more info about them at mdn
If you are looking for a good tutorial here is one.
ParseInt and Rounding, parseFloat
parseInt always rounds to the nearest integer. If you need decimal places there are a couple of tricks you can use. Here is my favorite:
2 places: `num = parseInt(num * 100) / 100;`
3 places: `num = parseInt(num * 1000) / 1000;`
For more information on parseInt look at mdn.
parseFloat could also be used if you do not want rounding. I assumed you did as the title was convert to an integer. A good example of this was written by #fr0zenFry below. He pointed out that parseFloat also does not take a radix so it is always in base10. For more info see mdn.
Try using replace() to replace a , with nothing and then parseFloat() to get the number as float. From the variables in OP, it appears that there may be fractional numbers too, so, parseInt() may not work well in such cases(digits after decimal will be stripped off).
Use regex inside replace() to get rid of each appearance of ,.
var a = parseFloat('1,700.00'.replace(/,/g, ''));
var b = parseFloat('500.00'.replace(/,/g, ''));
var sum = a+b;
This should give you correct result even if your number is fractional like 1,700.55.
If I go by the title of your question, you need an integer. For this you can use parseInt(string, radix). It works without a radix but it is always a good idea to specify this because you never know how browsers may behave(for example, see comment #Royi Namir). This function will round off the string to nearest integer value.
var a = parseInt('1,700.00'.replace(/,/g, ''), 10); //radix 10 will return base10 value
var b = parseInt('500.00'.replace(/,/g, ''), 10);
var sum = a+b;
Note that a radix is not required in parseFloat(), it will always return a decimal/base10 value. Also, it will it will strip off any extra zeroes at the end after decimal point(ex: 17500.50 becomes 17500.5 and 17500.00 becomes 17500). If you need to get 2 decimal places always, append another function toFixed(decimal places).
var a = parseFloat('1,700.00'.replace(/,/g, ''));
var b = parseFloat('500.00'.replace(/,/g, ''));
var sum = (a+b).toFixed(2); //change argument in toFixed() as you need
// 2200.00
Another alternative to this was given by #EpiphanyMachine which will need you to multiply and then later divide every value by 100. This may become a problem if you want to change decimal places in future, you will have to change multiplication/division factor for every variable. With toFixed(), you just change the argument. But remember that toFixed() changes the number back to string unlike #EpiphanyMachine solution. So you will be your own judge.
try this :
parseFloat(a.replace(/,/g, ''));
it will work also on : 1,800,300.33
Example :
parseFloat('1,700,800.010'.replace(/,/g, '')) //1700800.01
Javascript doesn't understand that comma. Remove it like this:
a.replace(',', '')
Once you've gotten rid of the comma, the string should be parsed with no problem.

Categories

Resources