PDA

View Full Version : Resolved ParceInt, ParceFloat, toFixed ? Trying to get whole number and decimal places.

BBoyd
01-18-2012, 02:26 AM
I'm fairly new to programming, I just started JavaScript and I did read the rules. I am a student and will not post my code asking someone to do my homework. :) I just need a little guidance.

For my assignment, when a webpage is loaded, it prompts the user to enter hours worked, their pay rate and tax rate, then use a function to calculate the net weekly pay, then display all numbers on the screen. Now I have this working and it appears on the screen, but I need to limit the hours worked to a whole number and the pay and tax rates need to only show 2 digits on either side of the decimal.

From searching I found a lot of information about ParceInt, ParceFloat and toFixed, but cannot get these to work. Either these are not correct or I'm not using them correctly.

Below are samples of 2 of the prompts. Can someone help me with this problem? Also is it better the handle this problem at the prompt or in the function or where it writes to the screen?

var hours_worked = prompt ("How many hours did you work?", "");
parseInt(hours_worked);
var pay_rate = prompt ("What is your pay rate?", "");
parseFloat(pay_rate);

Hopefully the subject was good enough and the content descriptive to understand when I'm trying to accomplish.

Brian

felgall
01-18-2012, 02:38 AM
parseInt is for converting numbers from one base to another for example parstInt('0xc') will return 12.

parseFloat is one way you could convert the text string input into a number but it disregards any non-numerics - so parseFloat('2.4getlost') will return 2.4

The first thing you need to do on your input is to validate that it is a number. It can then be converter from a string to a number using Number().

The number of decimal places JavaScript displays on the end of a number when you output it again as text is controlled using toFixed().

BBoyd
01-18-2012, 02:47 AM
Number()
toFixed().

Thanks! Let me experiment with these a little and I will be back.

BBoyd
01-18-2012, 03:18 AM
I'm missing something, but not sure what. I searched for examples on what you suggested and it looks simply, but I've tried many different ways and it doesn't work.

Here is the last code I tried. How my mind is viewing this problem is that the user is given a prompt to enter the number of hours worked. The assignment states "in whole amounts, no decimals, commas, or \$ signs allowed. Like: 40". The user enters say... 38.75 and Number() is suppose to take the string and convert it to a number and then the toFixed Method specifies how many digits are saved after the decimal.

If this thought is correct, how should the code be organized?

var hours_worked = prompt ("How many hours did you work?", "");
Number(hours_worked);
hours_worked.toFixed(0);

BBoyd
01-18-2012, 04:03 AM
I've been working on this longer than needed, but I have to figure it out. With a lot of trial and error, I have it working, but there is a lot more code than I think there should be.

var hours = prompt ("How many hours did you work?", "");
var hours2 = parseFloat(hours);
var hours3 = hours2.toFixed(0);

Can someone help me understand a better way with less code?

BBoyd
01-18-2012, 04:25 AM
I will need to give this subject a break and will return to it in the morning. 3+ hours on this has put me behind schedule.

Another note before logging off. The toFixed() sets the amount of digits of the right side of the decimal. How can you specify how many digits to the left side of the decimal? Another part of the assignment states "in decimal format with up to two digits to the left and two digits to the right of the decimal point", which would eliminating someone putting in a hourly pay rate of over \$100.

BTW... I read the rules about homework assignments and I feel that I have followed the rules and shown that I'm trying to work through the problem myself. I'm not trying to get someone else to do my homework so hopefully some experiences programmers will help guide me. I'm 43 years old and back in school taking 6 classes so the time I've spent on this one problem hurts. I could easily submit the assignment and get a 90, but I truly want to understand and learn this.

Brian

devnull69
01-18-2012, 08:24 AM
Don't worry about that rule ... you presented enough effort

But: You'll have to understand the difference between converting a number and validating a number. If the requirement says "no more than two digits on the left", it will have influence on the validity of the number. You have to check validity before converting the number.

Example: User input \$120.95 ... according to the requirements, this is an illegal number. If you just convert it to "two digits left and two digits right of the decimal point" you will get into trouble.

var hours = -1;
while(hours<0 || hours>100) {
var hours = parseFloat(prompt ("How many hours did you work?", ""));
}
// at this point the hours are valid
// convert toFixed
hours = hours.toFixed(0);

Philip M
01-18-2012, 08:31 AM
.toFixed() changes the number into a string value, and so is suitable only for display purposes. You cannot perform arithmetic calculations on a string value.

To round a number to x decimal places, while still retaining the number type-

<script type = "text/javascript">

function roundNumber(num, dec) {
var result = Math.round(num*Math.pow(10,dec))/Math.pow(10,dec);
return result;
}

</script>

felgall
01-18-2012, 08:37 AM
function roundNumber(num, dec) {
var result = Math.round(num*Math.pow(10,dec))/Math.pow(10,dec);
return result;
}

can be shortened to

function roundNumber(num, dec) {
return Math.round(num*Math.pow(10,dec))/Math.pow(10,dec);
}

Also you are better off defining functions using

roundNumber = function(num, dec) {
return Math.round(num*Math.pow(10,dec))/Math.pow(10,dec);
}

as the other way around doesn't work in all situations.

Philip M
01-18-2012, 08:52 AM
Also you are better off defining functions using

[code]roundNumber = function(num, dec) {
return Math.round(num*Math.pow(10,dec))/Math.pow(10,dec);
}

as the other way around doesn't work in all situations.

I am sure you are right, but I have never encountered such a situation. What have you in mind?

felgall
01-18-2012, 09:02 AM
I am sure you are right, but I have never encountered such a situation. What have you in mind?

for example it doesn't work inside an if statement

if (some_condition) {
function x() {return 'a';}
} else {
function x() {return 'b';}
}

will not work because JavaScript does not specify what value the function should have if defined that way. In browsers complying most closely to the standard that would be a syntax error. Other browsers might always run the first of the two function declarations regardless of the if condition and others the second. Some will just treat it all as the equivalent of alert(undefined).

Define the function the other way around and you gain better control of where the function applies and can define alternatives in an if statement.

As another example you can't rewrite a function defined that way and so cannot for example would not be able to include the above code with either style of function declaration inside of function x();

function x() {
if (some_condition) {
x = function() {return 'a';}
} else {
x = function() {return 'b';}
}
return x();
}

is also invalid but would be valid if the outer function were also defined the other way around.

There are further instances where placing function first in the declaration doesn't work but the above are the two that I am most familiar with.

Philip M
01-18-2012, 09:07 AM
Define the function the other way around and you gain better control of where the function applies and can define alternatives in an if statement.

Noted - thank you.

BBoyd
01-18-2012, 11:15 AM
I really appreciate the help you have giving me and one day I will pay it forward. Some of this is a little beyond me, but I will come back and visit this thread at a later date when it might make more sense.

The only issue that remains is stripping any characters that are not numbers from what the user enters in the prompt. I tested the page and entered \$40 in the hours worked and the display was NaN as well as the calculation amount that used this number.

Below is the code so far that all of you helped me with. I will be submitting 2 files for my assignment and hopefully the instruction will give me credit for this one. If not, what I did by myself should still be good enough for an 'A'.

This assignment is not due until Feb 19th, but I have a normal job while taking 6 classes this semester and so I need to work my butt off to get as far ahead as possible because the assignments are starting to take longer.

I will be back as I'm thirsty for knowledge so please remember me. :)

//I'm submitting 2 documents because some of the code/knowledge found in this assignment
//if this is not acceptable, the file (chap4assign1-MyOwnWork.html) is my own work.

//function to round numbers to specified amount that can be used in calculations.
//I learned more about math.round and math.pow on page 313-315 in the textbook.
function roundNumber(num, dec) {
var result = Math.round(num*Math.pow(10,dec))/Math.pow(10,dec);
return result;
}

//calculate gross pay & tax amount, then subtract tax amount from gross pay for net pay
function calculate_pay(hours,pay,tax)
{SNIP}...

var hours = -1;
while(hours<0 || hours>100) {
var hours = parseFloat(prompt ("How many hours did you work?", ""));
}
//at this point the hours are valid. round number to required decimal place.
hours = roundNumber(hours,0);

Philip M
01-18-2012, 11:29 AM
The only issue that remains is stripping any characters that are not numbers from what the user enters in the prompt. I tested the page and entered \$40 in the hours worked and the display was NaN as well as the calculation amount that used this number.

<script type = "text/javascript">

while (isNaN(hours) || hours < 0 || hours > 100) {hours = parseFloat(prompt("Please enter your hours worked - numbers only max.100",""))}
alert (hours.toFixed(2)); // for testing - result is a string
alert (roundNumber(hours,2)); // for testing - result is a number

function roundNumber(num, dec) {
return Math.round(num*Math.pow(10,dec))/Math.pow(10,dec);
}

</script>

The numbers after the decimal point are of course decimal fractions of an hour, and not minutes.
13.2 hours means 13 hours 12 minutes, not 13 hours 20 minutes.

hours = roundNumber(hours,0); is pointless - if you only want to use whole numbers of hours use parseInt() to start with.
But if you do use parseInt() you must remember to specify the radix - parseInt(mynumber,10) where 10 means decimal.
Otherwise if you user enters a leading zero the number (say 014) will be interpreted as octal.

BBoyd
01-18-2012, 11:46 AM
That's awesome Phillip and it works great.

I can read the textbook and follow along as if it all make sense, but then when I start working on an assignment, I'm like a deer in headlights. It is only during conversations like this in forums that I really learn from. This is my first thread here, but have started threads on other sites and the knowledge one can learn from others is just priceless.

Back to reading the next chapter. Javascript: A Beginners Guide and I'm on chapter 5 that covers operators so I will be back probably next week. Tomorrow I will move on to other subjects for about a week. I spend 1-3 days on a subject before putting it down. The benefit of working around the clock and getting ahead is being about to spend some continuous time on a subject.

Have a wonderful day!

Brian

BBoyd
01-18-2012, 12:02 PM
The numbers after the decimal point are of course decimal fractions of an hour, and not minutes.
13.2 hours means 13 hours 12 minutes, not 13 hours 20 minutes.

hours = roundNumber(hours,0); is pointless - if you only want to use whole numbers of hours use parseInt() to start with.
But if you do use parseInt() you must remember to specify the radix - parseInt(mynumber,10) where 10 means decimal.
Otherwise if you user enters a leading zero the number (say 014) will be interpreted as octal.

Thanks for the additional tips. I added all this to my notes for future reference.

Philip M
01-18-2012, 12:05 PM
You will find that if you approach the forum with the right attitude, really want to learn and not just copy and paste to get through some assignment, then people will be very willing to help you. :) Good luck!