numbers and text in same field - javascript

I can't get the numbers and text in same form field to force two decimal places or do Total figure.
This is the link.
I am trying to get the last 3 cells to work with two decimal places.
e.g. Total sq mt figure x Price should calculate the Cost cell.
Also want to get the Cost cell (NaN) working !
Thanks.

In general, you want to do something like this
function calc(val1, val2) { // this is NOT a replacement for your Calculate function
val1 = parseFloat(val1.replace(/[^\d\.-]/g, ''));
val2 = parseFloat(val2.replace(/[^\d\.-]/g, ''));
return (val1 * val2).toFixed(2);
}
NOTE: the above returns a STRING
and STOP redefining with Math.round in your code

var result = Math.round(num * 100.0) / 100.0;
Should format your number with two decimal places.

Related

When the result is round (1.10 1.30) does not display the 2nd decimal How do I do it?

My program (which uses Math.round) does not display the second decimal when the result is round (ex: 1.10, 1.30) while yes when the result is not round (ex: 1.24, 2.47). How to change this?
function calcAmount2() {
var userAmount2 = document.getElementById("amount2").value;
if (userAmount2 = Number(amount2.value)) {
document.getElementById("marginAmount2").textContent =
Math.round(userAmount2 * 3) / 100 + "€";
}
}
(expected)1.10, 1.30 instead of (actually) 1.1 1.3
(Math.round(userAmount2 * 3) / 100).toFixed(2) + "€";
toFixed sets the number to always have 2 decimals.
I believe this is a duplicate of Format number to always show 2 decimal places
You want to use .toFixed(2) it seems, though be aware the result will be a String.
I am not sure how specific your answer has to be, but I would recommend you to use this instead:
const res = Number(Math.round(userAmount2 +'e2')+'e-2');
This is because toFixed has the rounding problem for some values such as 21.005.
Let me prove it to you over here:
console.log(Number(Math.round(20.005 +'e2')+'e-2'));
console.log(20.005.toFixed(2));

How to simulate the result of a Google Sheet multiplication formula in Javascript?

If the value of f5 cell in a Google Sheet is 1.1000 (a number formatted to 4 decimal places) and the value of f6 is = f5 * 1.073, how can I ensure I get the same result multiplying those values in Javascript, eg:
var original_value = 1.1000;
var derivative_value = original_value * 1.073;
Specifically, my question is - will the result of the Javascript multiplication (derivative_value) be the same as the result of the Google formula (f6)? And if not, how can I make it so that it is?
Context / What I've Tried
For context, this question is part of a larger question I am trying to resolve for which I have set up this JSFiddle.
The JSFiddle has an input for the original_value and an input for the multiplier.
It outputs the result to four decimal places and adds trailing zeros where required (this is the required format for the result).
It is an attempt to check that the Javascript code I am writing will produce the same result as the Google Sheet formula.
[ The JSFiddle has been updated to also log decimal.js results to the console for comparison ]
Edit
There was a suggestion to use decimal.js but I'm not sure how it would be applied - something like the following?
var original_value = new Decimal(1.1000);
// some different multipliers for testing
var multiplier_a = new Decimal(1.073);
var multiplier_b = new Decimal(1.1);
// some different results for testing
var derivative_value_a = original_value.times(multiplier_a).toString();
var derivative_value_b = original_value.times(multiplier_b).toString();
console.log(derivative_value_a); // 1.1803
console.log(derivative_value_b); // 1.21
Is that any more accurate than plain Javascript original_value * multiplier? More importantly for this question, will it always simulate the same result that a Google Sheet formula produces?
JavaScript is using so called double precision float format (64 bit)- https://tc39.github.io/ecma262/#sec-terms-and-definitions-number-value
Google Sheets seem to use the same format, you can test it by =f6*1E13 - round(f6*1E13) to see that f6 is not STORED as a fixed number format, only FORMATTED
see Number.toFixed how to FORMAT numbers in Javascript
to generate some test data:
[...Array(10)].forEach(() => {
const f5 = 1.1
const x = Math.random() / 100
const f6 = f5 * x
console.log(x, f6.toFixed(4))
})
and compare in Google Sheet:
https://docs.google.com/spreadsheets/d/1jKBwzM41nwIEyatLUHEUwteK8ImJg334hzJ8nKkUZ5M/view
=> all rounded numbers are equal.
P.S.: you need to copy the console output, paste into the Sheet, use the menu item Data > Split text into columns... > Space, then multiply by 1.1 in 3rd column and finally format all numbers
After revisiting this I have updated the jsFiddle.
The main components of what I believe are a satisfactory solution are:
Convert both original_value and multiplier to decimal.js objects.
Do the multiplication using the decimal.js times method.
Do the rounding using the decimal.js toDecimalPlaces method.
Use the argument values (4,7) to define 4 decimal places with ROUND_HALF_CEIL rounding, equivalent to Math.round (reference)
For example:
var my_decimal_js_value = new Decimal(original_value).times(new Decimal(multiplier)).toDecimalPlaces(4, 7);
In order to add any necessary trailing zeros to the result, I use:
function trailingZeros(my_decimal_js_value) {
var result = my_decimal_js_value;
// add zeros if required:
var split_result = result.toString().split(".");
// if there are decimals present
if (split_result[1] != undefined) {
// declare trailing_zeros;
var trailing_zeros;
// get the amount of decimal numbers
decimals_present = split_result[1].length;
// if one decimal number, add three trailing zeros
if (decimals_present === 1) {
trailing_zeros = "000";
result += trailing_zeros;
}
// if two decimal numbers, add two trailing zeros
else if (decimals_present === 2) {
trailing_zeros = "00";
result += trailing_zeros;
}
// if three decimal numbers, add one trailing zero
else if (decimals_present === 3) {
trailing_zeros = "0";
result += trailing_zeros;
}
// if four decimal numbers, just convert result to string
else if (decimals_present === 4) {
result = result.toString();
}
}
// if there are no decimals present, add a decimal place and four zeros
else if (split_result[1] === undefined) {
trailing_zeros = ".0000";
result += trailing_zeros;
}
return result;
}
I am still not absolutely certain that this mimics the Google Sheet multiplication formula, however using decimal.js, or another dedicated decimal library, seems to be the preferred method over plain JavaScript (to avoid possible rounding errors), based on posts such as these:
http://www.jacklmoore.com/notes/rounding-in-javascript
Is floating point math broken?
https://spin.atomicobject.com/2016/01/04/javascript-math-precision-decimals

Add fixed 2 decimals to a number using javascript

I want to have 2 decimals in a number.
I tried using :
var number = (123).toFixed(2);
but it returns it in a string format. I want them to be numbers.
Also I tried using:
var number= parseFloat((123).toFixed(2));
but this removes the decimals if it is 0.
I want to show the numbers as decimals with fixed 2 decimals, also convert those numbers to toLocaleString("bn-IN-u-nu-latn")
For example:
number = 123456
output : 1,23,456.00
That's impossible. A number won't display trailing zeros past the decimal point. Only a string will.
For example, observe this output:
document.write(0.00); // output as a number, is 0
document.write("<br>");
document.write("0.00"); // output as a string, is 0.00
If you want a number to be rounded to two decimal places, but also have trailing zeros when needed, you must convert to a string before you output, which means (123).toFixed(2) is all you need.
Edit: To round the number, but also use a locale format. Use .toLocaleString() like such:
(0.00).toLocaleString("bn-IN-u-nu-latn", {
minimumFractionDigits:2,
maximumFractionDigits:2
});
Try :
var number = +parseFloat(Math.round(123 * 100) / 100).toFixed(2);
You can try this ..
Html
Value: <input type="text" id="myText" value="">
Javascript
<script>
num = 125;
num=num+1;
var R = num.toFixed(2); // returns 126.00
document.getElementById("myText").value = R;
</script>
Please see below screen......

How to round my values with Math.ceil()?

got the following code:
var total = 0;
var $parent = $(this).closest('ul');
$parent.find('input:checked').each(function() {
total += parseInt($(this).val() * parseInt(115, 10) / parseInt(100, 10) / parseInt(36, 10));
});
$parent.find('span[class^=total]').html(Math.ceil(total));
The code checks the value of my inputs and with parseInt i convert them to another value (its a fixed price converted to monthly costs over 3 years).
This works but the value which i output in my html at the end wont get rounded up:
So my question is, how i can round up the value of my html output.
You're using parseInt() which will round down to the nearest int by default. If the original values are floating points you need to use parseFloat() instead.
$parent.find('input:checked').each(function() {
total += parseFloat($(this).val()) * 115 / 100 / 36;
});
Working example
Also note that you don't need to call parseInt() or parseFloat() on literal integer values.

Jquery - set a variable with a decimal in front

In Jquery, how do you take a variable and set a second variable with a decimal in front of the value of the first variable.
For example I have a variable that is set from a form input values. I named this variable subTotal. Now I want to take that variable and set another variable with a decimal in front of it so I can calculate a percentage by multiplying another input value.
So here is some of the code for example
var subTotal = self.calculateTotalFor(elems);
total += (quantity - 1) * NewVariable;
self.calculateTotalFor(elems); comes from the input on the form
NewVariable would be Subtotal with a decimal in front.
Try :
var subTotal = self.calculateTotalFor(elems), total = 0;
total += (quantity - 1) * NewVariable;
or
total += parseFloat((quantity - 1) * NewVariable);
Try this
var NewVariable = parseFloat("." + Subtotal);
This will take "." and your Subtotal value and perform a string
append
parseFloat will convert the string to a floating point number

Categories