Round every textbox to 2 decimal places - javascript

This is probably really simple, but for the life of me I can't work out how to do it. So here goes: I have a large form with lots of text boxes, which are all currency based and so need to be rounded off to 2 decimal places. The values of these textboxes are all generated dynamically by some JavaScript functions I wrote, and I can use .toFixed(2); to round them up/down to 2 decimal places. However, it gets tiring and repetitive to have to put this after working out each value of each textbox. How could I write a simple piece of JavaScript (can be jQuery) to target all the textboxes and round them ALL to 2 decimal places?
Thanks for any help :)
P.S Sorry for the lack of any code, but there isn't really any to show, as its all locked up in big functions. But here's what I'm essentially doing:
function workOutSomeVal() {
// lots of code to work out values and stuff
var finalValue = some mathematical equation to work out value;
var anotherValue = a different value;
$(".some-textbox").val((finalValue).toFixed(2));
$(".another-textbox").val((anotherValue).toFixed(2));
} // my question is, how could I get rid of .toFixed(2) and put in a generic statement somewhere to target all the textboxes?

You can have a function you call that does this:
function roundTextBoxes() {
$("input[type=text]").val(function() {
return (+this.value).toFixed(2);
});
}
...and then call that any time any of them changes. Live Example: http://jsbin.com/toyoc/1
It will probably mean that sometimes, a user looking at the page who does the mental arithmetic will find that it doesn't quite add up...

You can give a common class to all the textboxes which you want to be "roundable", and then select then using that class and apply your rounding logic to each of them.
// let's say all the roundable textboxes have the class "roundable"
$('.roundable').each(function() {
var value = // some mathematical equation to work out value
$(this).val((value).toFixed(2));
});

Another appoach:
Why don't you put value.toFixed(2) at the end of your calculation ?
var finalValue = function(){
// var value = some calculation
return value.toFixed();
}
Or - if you need the full value elsewhere, create a new function:
var finalValueView = function(){
finalValue().toFixed(2);
}
function workOutSomeVal() {
// ...
$(".some-textbox").val(finalValueView);
}

Use Math.round(num * 100) / 100

Related

How to Unify Kotlin and Long.js Division Results

I have an issue,
I have a number that I wish to divide by 49 as shown in the code below:
// in Javascript:
let referenceNumber= 3487039819743582477;
let division = referenceNumber /49;
//I am using https://github.com/dcodeIO/long.js
//Now when I do the following with the Long.js library:
let longValue = Long.fromValue(division); //Long.js gave me 71164077953950662 as the result
//Now, in Kotlin:
val longValue = division.toDouble().toLong(); //Kotlin gave me 71164077953950664 as result
// As you can see, there is a difference of 2 between the two programming languages.
Which is the correct value here and How do I rectify this? I want both languages to give me exact value all the time after division and conversion to long
Thank you.
The problem is that you are doing toDouble(), which adds imprecision.
println(3487039819743582477 / 49) prints 71164077953950662.
If you want to know about Double and imprecision, check out https://floating-point-gui.de/.

How to swap two numbers using javascript function with one parameter

My Requirement is
I want to display this output when I gave a(0) the output should come 5 and when I gave a(5) the output should come 0.
a(0) = 5
a(5) = 0
like this
Hint:
Using this function
function A(num){}
like this
Please Help me how to do this I'm new in JS
Please give me different kind of solutions its more useful to my career.
function swap (input) {
if( input == 0)
return 5;
return 0;
}
i think there is no description needed
I think I see what you are getting at.
You want to input one variable into a function, and return another variable that is not defined yet. Then you want to define that variable by inputting it into the same function, and get the first input as the output. And so you should end up with 2 outputs.
Now this is technically impossible, because there are undefined variables at play. However, programming is about imagination and I think I have a solution (it's technically a hack but it will work):
var i = 1;
var output1;
var output2;
function swap(input) {
function func1(input) {
output2 = input;
i++;
}
function func2(input) {
output1 = input;
i = 1;
alert(String(output1) + "\n" + String(output2));
}
if (i === 1) {
func1(input);
}
else if (i === 2) {
func2(input);
}
}
while(true) {
swap(prompt("Enter your first input (this will be your second output):"));
swap(prompt("Enter your second input (this will be your first output):"));
}
The swap function goes back and forth between the values 1 and 2 in the variable i. That is how it keeps track of first or second inputs and their exact opposite outputs. The input, or parameter of the swap function is whatever the user types into the prompt boxes. Feel free to make it user-friendly, this is just the dirty code behind it. The reason they are outputted together is because the second input is undefined, and so the machine cannot guess what you were going to input. So first my little program collects all the data and just reverses the order when it is time to output. But to the user who knows nothing about JavaScript and what is going on underneath the hood, this would work perfectly in my opinion.
This should work for any data types inputted, I tested it myself with objects, strings, numbers, and arrays. Hope this helps!!
Shorter alternative to #mtizziani's answer:
let swap = x => !x * 5 // yes this is all
console.log(swap(0));
console.log(swap(5));
We toggle the input, so x is now 1 or 0
We multiple by 5.
Job done.

Displaying Math.random() in h1 tag jQuery

All I'm trying to do is display the math.random number in the h1 tag by using jQuery and for some reason it's not working I'm not sure whats going wrong. For some reason when I take out the function it works but why is that?
HTML
<h1></h1>
jQuery
function time(){
var number = Math.floor(Math.random());
$('h1').text(number);
}
You are using $ which is a jquery selector in a form that doesnot know about JQuery .
So please use this code instead :
function Thetime(){
$(document).ready(function() {
var number = Math.floor(Math.random());
$('h1').text(number);
});
}
Hope this will solve your problem .
a side note : you are flooring the generated number , that might always lead to ZERO , So you can also only use Math.random() instead of Math.floor(Math.random());
Thanks
You need to actually call the time() function to make it perform its operations.
Here is your code running:
function time(){
var number = Math.floor(Math.random());
$('h1').text(number);
}
// call your function to run it
time();
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<h1></h1>
NOTE: You may notice that your number is always 0. This is because Math.random() creates a float between 0 and 1 (eg: 0.22378). Likewise, Math.floor() will take any floating point number and round it down to the nearest integer. So a random number like 0.22378 will always be floored to 0. If you want to randomize between a range of whole numbers you need to multiply your random number by your maximum then floor the result.
var max = 30;
var number = Math.floor(Math.random() * max);
#ScottMarcus answered the question, all I had to do was add a document.ready to the function. Just going to leave this up for any new beginning coders.

fnumber.toFixed(2) does not always truncate the value to two decimal points

What can be done to prevent numbers like this appearing in my output?
Here is my javascript code.
$("#TaskListing table tr td#Begin input").each(function (index, element) {
var theRow = $(element).parent().parent();
var thePercent = $(theRow).children("tr td#Percent:first");
currentvalue = $(theRow).data("millisecs");
fnumber = currentvalue / totalTimeMs;
thePercent.text( 100 * fnumber.toFixed(2));
});
I thought that using fnumber.toFixed(2) would prevent values like this (28.0000000000004 ) from appearing but yet they appear from time to time.
Change your code to use toFixed like this.
thePercent.text( (100 * fnumber).toFixed(2) );
You want to perform the calculation first then send it to the toFixed() method
The answer is to use thePercent.text( (100 * fnumber).toFixed(2) );
Not sure what the issue is with the other way of doing it, maybe it's a problem with .toFixed() for values that can't be expressed without using a repeating fraction.

Javascript removing decimals in knockout binding

I've seen there are quite a few questions about decimal precision and display in Javascript. the thing is that I came to a solution that I thought it was gonna be enough for me'
The key thing is that I'm trying to parse to a string to round and then back to numbers using expressions like this.
return parseFloat(num.toFixed(2));
But there are some cases that it doesn't work as expected. To be honest I'm not sure if it has to do with the way I'm using ko or the javascript code for parsing I put in place. But let's say that in the below fiddle you type 14.385 in the upper text box, both fields will be properly rounded and will display the correct number of decimals, but without deleting the number you add 3333 (that means 14.393333) and the upper one won't be rounded. That's just an example because there are some strange behaviours.
Yo can see the fiddle here http://jsfiddle.net/RTexF/
Thanks
Edit. I add the code as per judgeja indication (I didn't understand the reason to ask for a code when you link fiddle, I see the point now)
The script
var decimalValue = 0.25;
function ViewModel() {
var self = this;
self.submittedValue = ko.observable(decimalValue);
self.percentage = ko.computed({
read: function() {
alert('read');
if (isNaN(parseFloat(self.submittedValue())))
return '';
var num = self.submittedValue() * 100;
return parseFloat(num.toFixed(2));
},
write: function(value) {
alert('write');
value = isNaN(value) ? '' : parseFloat((value / 100).toFixed(4));
self.submittedValue(value);
},
owner: self
});
}
ko.applyBindings(new ViewModel());
And the html
<p><input data-bind="value:percentage"></input></p>
<p><input data-bind="value:submittedValue"></input></p>
EDIT:
Know that it's an old one but I wanted to note that adding this to the write method
self.percentage.notifySubscribers(value);
it fixes the issue (ideally we could check against the current value and just notifiy if it actually changes)
Fiddle : http://jsfiddle.net/RTexF/1/ and http://jsfiddle.net/RTexF/2/
It may help you to think about this if you put an alert("read") in the read: and an alert("write") in the write: and then run your example again.
When you change the top box the first time the bottom box is written to through the write and then the top box is re-computed as the submittedValue observable has changed and you'll see the read for percentage being hit.
Next time you edit the top box the write will be hit again as we're changing the value, which makes sense, but since the submittedValue isn't changed, then the read won't happen again as the observable it depends upon won't have changed.

Categories

Resources