jQuery divide a number but keep decimals - javascript

I'm hoping for a bit of help with this issue I have.
I basically have a number... say 3000 and I want to display 30.00 on the front end without changing my variable (lots of reasons why I can't change it, I've just simplified this for the question)
HTML:
<span class="number"></span>
JS:
var three = 3000;
$('.number').append(three/100);
This returns '30' to my span. How can I keep the decimal points?
Thanks!

Number.toFixed() should do the trick:
var three = 3000,
result = (three/100).toFixed(2);
$('.number').append(result);
If you're concerned about toFixed() rounding, there are a lot of SO threads covering that topic.

Related

How to "unformat" a numerical string? JavaScript

So I know how to format a string or integer like 2000 to 2K, but how do I reverse it?
I want to do something like:
var string = "$2K".replace("/* K with 000 and remove $ symbol in front of 2 */");
How do I start? I am not very good regular expressions, but I have been taking some more time out to learn them. If you can help, I certainly appreciate it. Is it possible to do the same thing for M for millions (adding 000000 at the end) or B for billions (adding 000000000 at the end)?
var string = "$2K".replace(/\$(\d+)K/, "$1000");
will give output as
2000
I'm going to take a different approach to this, as the best way to do this is to change your app to not lose the original numeric information. I recognize that this isn't always possible (for example, if you're scraping formatted values...), but it could be useful way to think about it for other users with similar question.
Instead of just storing the numeric values or the display values (and then trying to convert back to the numeric values later on), try to update your app to store both in the same object:
var value = {numeric: 2000, display: '2K'}
console.log(value.numeric); // 2000
console.log(value.display); // 2K
The example here is a bit simplified, but if you pass around your values like this, you don't need to convert back in the first place. It also allows you to have your formatted values change based on locale, currency, or rounding, and you don't lose the precision of your original values.

Purpose of dividing by 1 javascript

I was working on a simple programming exercise my teacher gave us, and I noticed several times that in Javascript, I have to divide a number by 1, otherwise it will return a ridiculous value. Any explanations?
I have a jsfiddle
http://jsfiddle.net/TpNay/1/
var widthrand=Math.floor(Math.random()*widthRange);
width=widthrand + document.getElementById('width').value/1;
If you look at line 22, and take out the divide by 1, and click generate, it will return ridiculous lengths
Thanks
It makes JavaScript type juggle forcing the value of document.getElementById('width').value to become numeric.
A better way to do it would be parseInt(document.getElementById('width').value, 10)

Javascript: How do I code a script where the user inputs a number and it returns three other numbers?

I'm not even quite sure how I can make myself clear and I do apologize... but I have been searching all over the internet for a similar JavaScript code and I'm not even quite sure how to phrase the question ...
Basically, I want the user to input one thing, and I want something else to pop up.
As an example, the user would type in a number, let's say "10" into a text field or drop-down menu and then three other numbers would pop up, such as 15.25, 16.50, and 17.75 (either in pop window form, or just in a plain sentence, or in other text fields ... it doesn't really matter).
What I'm doing is I want to post an estimate calculator for loan payments on a website (with options for 30 day, 60 day, and 90 day payoff options).
There's no math involved in this code whatsoever (I understand if I have to input a lot of numbers - I already have those!). I don't want to create a calculator, because I think a calculator would be more complicated (I'm aiming for simple!) ... The loan fees and interest vary from one group of numbers to another, so if it were to be a calculator the script might get really complicated (because we're not looking at a easy 1 + 1 = 2 equation ... it's more like 1 + 1.50 + 1.00 = 3.50, or 10.00 + 4.00 + 1.25 = 15.25, or even 30.00 + 6.00 + 1.75 etc., there's no consistency).
So I'm figuring a simpler way around this beast would be to have the numbers readily available, with no calculations. So if they enter in a 1, the result they would get be 3.50, 4.50, and 5.50.
I don't know, that might be asking a bit much too....
Thank you in advance for your time and help.
In a simplest form it will look like this:
var magic_box = {
'1': [3.50, 4.50, 5.50],
'2': [2.50, 34.50, 5.55],
'3': [1.50, 0.50, 15.50]
};
var what = prompt( 'Tell me the magic number!' );
alert( magic_box[ what ] );
We use hash-map (aka javascript object) each element of which is an array, and each element of those arrays is your desired number.
Then, we give user a popup with question and store his answer (or his input) into variable.
Then we use this variable as a key for our hash-map.
p.s.: there are several issues with solutions above, so its purely for educational reasons.
building on #c69's answer, if there is a range for each set of numbers then add min, max values to the three numbers, loop through array, do an inclusion check, stop on row where number is in range

Javascript issue with math calculations

Why is it if I do this in javascript, I get the following result:
1234.56 * 10 = 12345.599999999999
It should be 123456. How can I get around this problem?
Thanks.
Floating points are not exact, since there are ifinite numbers at their range [or in any range to be more exact], and only a finite number of bits to store this data.
Have a look at what every programmer should know about floating point arithmetics.
Another easy solution:
parseFloat((1234.56 * 10).toPrecision(12))
and the result will be: 12345.6, and YES... it works with decimal numbers.
As the others said, floating points and so on.
Easy solution would be to do something like this:
var answer = parseInt(1234.56 * 10);
Or just use Math.round?
All numbers in JS are internally defined by float and drop the less significant digits if needed.
(10000000000000000000000000000 + 1) == 10000000000000000000000000000
// this will return true
And javascript is well known for droping bits quite often in numbers. So handle with care

Is there a way to truncate scientific notation numbers in Javascript?

As you all know since it is one of the most asked topic on SO, I am having problems with rounding errors (it isn't actually errors, I am well aware).
Instead of explaining my point, I'll give an example of what possible numbers I have and which input I want to be able to obtain:
Let's say
var a = 15 * 1e-9;
alert(a)
outputs
1.5000000000000002e-8
I want to be able to obtain 1.5e-8 instead, but I cannot just multiply by 10e8, round and divide by 10e8 because I don't know if it will be e-8 or e-45 or anything else.
So basically I want to be able to obtain the 1.5000002 part, apply toFixed(3) and put back the exponent part.
I could convert into a string and parse but it just doesn't seem right...
Any idea ?
(I apologize in advance if you feel this is one of many duplicates, but I could not find a similar question, only related ones)
Gael
You can use the toPrecision method:
var a = 15 * 1e-9;
a.toPrecision(2); // "1.5e-8"
If you're doing scientific work and need to round with significant figures in mind: Rounding to an arbitrary number of significant digits
var a = 15 * 1e-9;
console.log(Number.parseFloat(a).toExponential(2));
//the above formula will display the result in the console as: "1.50e-8"

Categories

Resources