How to make 5509.099999999999 as 5509.09 using javascript - javascript

How to make 5509.099999999999 as 5509.09 using javascript.

Lots of mathy options that end up with .1 so how about;
var f = 5509.099999999999
if ((f = f.toString()).indexOf(".") >= 0)
f = f.substr(0, 3 + f.indexOf("."))
print(parseFloat(f))
>>5509.09

Have you tried this?
var value = 5509.099999999999;
var str = value.toString();
var result = str.substr(0,7);
Then if you need it to be a float again you can do:
var FinalAnswer = parseFloat(result);
You don't need all these variables, but that is the step by step.

var result = (Math.round((5509.09999 * 100) - 1)) / 100;

You could use .toFixed(2) but this will round the value, so in your example you'll end up with 5509.10 instead of 5509.09.
The next best option is to use Math.floor(), which truncates rather than rounding. Unfortunately, this only gives integer results, so to get the result to 2 decimal places, you'd need to multiply by 100, then use Math.floor(), and then divide by 100 again.
var value = 5509.099999999999;
var result = Math.floor(value*100)/100;
[EDIT]
Hmm, unfortunately, the above doesn't work due to problems with floating point precision -- even just the first step of multiplying it by 100 gives 550910.
Which means that the best answer is likely to be converting it to a string and chopping the string into bits.
var value = 5509.099999999999;
var str_value = value.toString();
var bits = str_value.split('.');
var result = bits[0]+"."+bits[1].substr(0,2);
I wouldn't normally suggest doing string manipulation for this sort of thing, because it is obviously a maths problem, but given the specific requirements of the question, it does seem that this is the only workable solution in this case.

You can truncate the number to a certain number of decimal places using this function:
function truncateNumber(number, digits){
var divisor = Math.pow(10,digits);
return Math.floor(number*divisor)/divisor;
}
If you want to round the number instead, you can use JavaScript's built in Number.toFixed function. If you always want the number a certain number of digits long, you can use the Number.toPrecision function.

if you want to take two decimal places, you can use .toPrecision(n) javascript function, where n is the total number of digits desired.
so, for your example, you'd have to do
var x = 5509.099999999999;
x = x.toPrecision(6);
this, however, rounds results in 5509.10

Related

Javascript: "+" sign concatenates instead of giving sum of variables

I am currently creating a site that will help me quickly answer physics questions.
As it happens, the code didn't run as expected, here is the code
if (option == "dv") {
var Vinitial = prompt("What is the Velocity Initial?")
var acceleration = prompt("what is the acceleration?")
var time = prompt("what is the time?")
Vfinal = Vinitial + acceleration * time
displayV.innerHTML = "v= vf= " + Vfinal + "ms" + sup1.sup();
}
Now, let's say Vinitial was 9, acceleration was 2, and time was 3.
When the code runs, instead of getting 15 for "Vfinal", I get 96.
I figured out that it multiplies acceleration and time fine, and then just concatenates the 9 at the beginning, with 6 (the product of 2 * 3).
I have fixed it for now by using
Vfinal = acceleration * time - (-Vinitial)
which avoids using the "+" sign, but I don't want to have to keep doing this. How do I fix it?
you are dealing with strings here, and math operations on strings will mess up. Remember when ever you are doing math operations you have to convert the data into actual numbers and then perform the math.
Use parseInt() more Details here
Your code should change to
Vfinal = parseInt(Vinitial,10) + parseInt(acceleration,10) * parseInt(time,10);
Edit 1: If the numbers are decimal values then use parseFloat() instead
So the code would be
Vfinal = parseFloat(Vinitial) + parseFloat(acceleration) * parseFloat(time);
Object-Oriented JavaScript - Second Edition: As you already know, when you use the plus sign with two numbers, this
is the arithmetic addition operation. However, if you use the plus
sign with strings, this is a string concatenation operation, and it
returns the two strings glued together:
var s1 = "web";
var s2 = "site";
s1 + s2; // website
The dual purpose of the + operator is a source of errors. Therefore,
if you intend to concatenate strings, it's always best to make sure
that all of the operands are strings. The same applies for addition;
if you intend to add numbers, make sure the operands are numbers.
You can use "+" operator with prompt() to convert returned values from string to int
var Vinitial = +prompt("What is the Velocity Initial?");
var acceleration = +prompt("what is the acceleration?");
var time = +prompt("what is the time?");
Explanation:
var a = prompt('Enter a digit');
typeof a; // "string"
typeof +a; // "number"
If you will enter non-digit data +a gives you NaN. typeof NaN is "number" too :)
You will get the same result with parseInt():
var Vinitial = parseInt(prompt("What is the Velocity Initial?"), 10);
var acceleration = parseInt(prompt("what is the acceleration?"), 10);
var time = parseInt(prompt("what is the time?"), 10);
developer.mozilla.org: parseInt(string, radix);
string: The value to parse.
radix: An integer between 2 and 36 that represents the radix (the base in mathematical numeral systems) of the above mentioned string.
Specify 10 for the decimal numeral system commonly used by humans.
Always specify this parameter to eliminate reader confusion and to
guarantee predictable behavior. Different implementations produce
different results when a radix is not specified, usually defaulting
the value to 10.
Epilogue:
Object-Oriented JavaScript - Second Edition: The safest thing to do is to always specify the radix. If you omit the radix, your code
will probably still work in 99 percent of cases (because most often
you parse decimals), but every once in a while it might cause you a
bit of hair loss while debugging some edge cases. For example, imagine
you have a form field that accepts calendar days or months and the
user types 06 or 08.
Epilogue II:
ECMAScript 5 removes the octal literal values and avoids the confusion
with parseInt() and unspecified radix.
The Problem is, Your value has been took it in a form of string .. so convert your value into Int using parseInt(accelaration).. then it will work ..
Vfinal = parseInt(Vinitial) + parseInt(acceleration) * parseInt(time)
//use ParseInt
var a=10,b=10;
var sum=parseInt(a+b);
ex:
parseInt(Vinitial + acceleration) * time

How can I parse a string as an integer and keep decimal places if they are zeros?

I have these strings: "59.50" & "30.00"
What I need to do is convert them to integers but keep the trailing zeros at the end to effectively return:
59.50
30.00
I've tried:
Math.round(59.50 * 1000) / 1000
Math.round(30.00 * 1000) / 1000
but ended up with
59.5
30
I'm assuming I need to use a different method than Math.round as this automatically chops off trailing zeros.
I need to keep these as integers as they need to be multiplied with other integers and keep two decimals points. T thought this would be fairly straight forward but after a lot of searching I can't seem to find a solution to exactly what I need.
Thanks!
Your premise is flawed. If you parse a number, you are converting it to its numerical representation, which by definition doesn't have trailing zeros.
A further flaw is that you seem to think you can multiply two numbers together and keep the same number of decimal places as the original numbers. That barely makes sense.
It sounds like this might be an XY Problem, and what you really want to do is just have two decimal places in your result.
If so, you can use .toFixed() for this:
var num = parseFloat("59.50");
var num2 = parseFloat("12.33");
var num3 = num * num2
console.log(num3.toFixed(2)); // 733.64
Whenever you want to display the value of the variable, use Number.prototype.toFixed(). This function takes one argument: the number of decimal places to keep. It returns a string, so do it right before viewing the value to the user.
console.log((123.4567).toFixed(2)); // logs "123.46" (rounded)
To keep the decimals - multiply the string by 1
example : "33.01" * 1 // equals to 33.01
Seems you are trying to retain the same floating point, so better solution will be some thing like
parseFloat(string).toFixed(string.split('.')[1].length);
If you want numbers with decimal points, you are not talking about integers (which are whole numbers) but floating point numbers.
In Javascript all numbers are represented as floating point numbers.
You don't need the trailing zeros to do calculations. As long as you've got all the significant digits, you're fine.
If you want to output your result with a given number of decimal values, you can use the toFixed method to transform your number into a formatted string:
var num = 1.5
var output = num.toFixed(2) // '1.50'
// the number is rounded
num = 1.234
output = num.toFixed(2) // '1.23'
num = 1.567
output = num.toFixed(2) // '1.57'
Here's a more detailed description of toFixed: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number/toFixed

Convert a Decimal number to float and truncate it

I have a number
For example:
8183
What I need is to convert it to a float number-
For example 8183
(8183).toFixed(2);
will return me
8183.00
But I need to truncate it further, so the final number will be
8.18
So basically I need to make it float number with just 2 decimal places.
I tried using the Math.floor and ceil but couldnt figure it out!
Well what you're trying to accomplish is not completely clear, but I think that if you start by dividing by 1000, then call toFixed on it, it will give you the desired result.
var before = 8183;
var after = (before / 1000).toFixed(2); //8.18
You could divide by 10 until you are less than 10:
var digits = 8183;
while((digits = digits/10) > 10) {}
digits = digits.toFixed(2); // 8.18
For negative numbers, you could want to store a boolean value and use Math.abs(digits).
For numbers less than 0, you would want to multiple instead of divide.
If all you really want is scientific notation use toExponential(2)

Javascript is treating variables as Strings, why?

I have the variable y, which is a subtotal. Its value is different depending on what happens with the html, but throughout the script I declared it like this:
var y = 21.78;
etc. Why is it that on my last equation where I add up the total, it treats them as strings when I want to add the values?
var tax = (0.055*y).toFixed(2);
var totalprice = y+tax;
/* totalprice holds "21.781.20" instead of 22.98 */
According to:
https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Number/toFixed
toFixed() returns:
A string representation of number that does not use exponential
notation and has exactly digits digits after the decimal place.
thus, y+tax is cast to a string since one of the operands is a string.
In my opinion, this would make sense as Javascript's intrinsic numeric types do not have the ability to store a specific number of decimal place digits, so a string would be the most appropriate data structure to store this with.
I would advise you do all your addition before calling toFixed(), since the method is most suitable for formatting display output.
var taxRate = 0.055;
var subtotal = 21.78;
var tax = (taxRate * subtotal).toFixed(2),
totalprice = ((1+taxRate) * subtotal).toFixed(2);
document.write(totalprice);
The .toFixed() method returns a string. Try applying that method as the last step after all other calculations.
Here's a simple fix. Put '+' in front of the tax variable to convert it to a number.
var y = 21.78;
var tax = (0.055*y).toFixed(2);
var totalprice = y+ (+tax);
totalprice === 22.98;
If you don't want any rounding errors when you use toFixed, then include this re-implementation of it in your script.
http://bateru.com/news/2012/03/reimplementation-of-number-prototype-tofixed/
In my experience, if there's any chance available, Javascript will see the "+" sign as concatenate rather than addition. It's driven me nuts on more than one occasion. I will generally do this rather than chance concatenation:
var totalprice = parseInt(y)+parseInt(tax);
When letter replaces value, multiply with 1 when you're in need of +.
var totalprice = (y*1) + tax .
Other operands work fine, it's just the + operand that needs special treatment when variable replace value.

Subtraction in JavaScript only returns two digits of the thousands

I have two variables holding integer values:
x = 36,000;
y = 18,045.40;
this is how i subtract:
z = parseInt(x) - parseInt(y);
the result is 15.
If i remove the parseInt the result is 'Nan'.
How do I go about subtracting x with y without rounding off or removing thousands?
many thanks.
Don't put commas in your numbers.
The code you have posted won't even run. I would recommend pulling the ,s out of your numbers and using parseFloat instead. This appears to give the result you want. Demo here:
http://jsfiddle.net/yVWA9/
code:
var x = 36000;
var y = 18045.40;
alert(parseFloat(x) - parseFloat(y));
There is no separator for thousands in Javascript. Your variables are either holding strings and not integer values or you are getting syntax error.
If you have strings and they cannot be changed (like received from service, etc.) then try this:
x = "36,000";
y = "18,045.40";
// remove commas and convert to numbers
function norm(num) { return +num.replace(',', ''); }
console.log(norm(x) - norm(y));

Categories

Resources