Doing math with Time using js - javascript

I have the following code:
HTML:
<form onsubmit="return false;">
<div class="col-5">
<label>
Page Time
<input id="pageTime" name="pageTime" type="time" step="1" tabindex="9">
</label>
</div>
<div class="col-5">
<label>
Ack Time
<input id="ackTime" name="ackTime" type="time" step="1" tabindex="10">
</label>
</div>
<div class="col-5">
<label>
Arrival Time
<input id="arrivalTime" name="arrivalTime" type="time" step="1" tabindex="11">
</label>
</div>
<div class="col-5">
<label>
Start Replace / Root Cause Found
<input id="startReplace" name="startReplace" type="time" step="1" tabindex="12">
</label>
</div>
<div class="col-5">
<label>
Replaced / Repair Completed
<input id="replaced" name="replaced" type="time" step="1" tabindex="13">
</label>
</div>
<div class="col-4">
<label>
Engagement
<input type="text" id="engagement" name="engagement" value="" readonly="readonly" />
</label>
</div>
<div class="col-4">
<label>
Arrival
<input type="text" id="arrival" name="arrival" value="" readonly="readonly" />
</label>
</div>
<div class="col-4">
<label>
Investigation
<input type="text" id="investigation" name="investigation" value="" readonly="readonly" />
</label>
</div>
<div class="col-4">
<label>
Mitigate
<input type="text" id="mitigate" name="mitigate" value="" readonly="readonly" />
</label>
</div>
<div class="col-1" style="text-align: center">
<label>
Total Ops Phases
<input type="text" name="totalOpsPhases" id="totalOpsPhases" value="" readonly="readonly" />
</label>
</div>
<div class="col-submit">
<button class="submitbtn" tabindex="14" onclick="opsTime();">Do the Math</button>
</div>
</form>
JS:
function toSeconds(time_str) {
// Extract hours, minutes and seconds
var parts = time_str.split(':');
var sum = 0;
// compute and return total seconds
for (c = 0; c <= 2; c++) {
if (c === 0) {
sum += parts[0] * 3600;
} else if (c === 1) {
sum += parts[1] * 60;
} else if (c === 2) {
if (parts[2] !== 'undefined') {
sum += parts[2];
}
}
}
return sum;
}
function opsTime() {
var time = [document.getElementById('pageTime').value, document.getElementById('ackTime').value, document.getElementById('arrivalTime').value, document.getElementById('startReplace').value, document.getElementById('replaced').value];
// Created an array to easily do the math :)
// Array mapping:
// 0 = pageTime
// 1 = ackTime
// 2 = arrivalTime
// 3 = startReplaceTime
// 4 = replacedTime
for (i = 0; i <= 4; i++) {
if (i === 4) {
var start = time[0];
var end = time[4];
} else {
start = time[i];
end = time[i + 1];
}
var startSec = toSeconds(start);
var endSec = toSeconds(end);
var difference = Math.abs(endSec - startSec);
// format time differnece
var result = [
Math.floor(difference / 3600), // an hour has 3600 seconds
Math.floor((difference % 3600) / 60), // a minute has 60 seconds
difference % 60
];
// 0 padding and concatation
result = result.map(function (v) {
return v < 10 ? '0' + v : v;
}).join(':');
var res = [];
res[i] = result;
}
document.getElementById('engagement').value = res[0];
document.getElementById('arrival').value = res[1];
document.getElementById('investigation').value = res[2];
document.getElementById('mitigate').value = res[3];
document.getElementById('totalOpsPhase').value = res[4];
}
What I'm trying to do is to pick the times filled in the inputs and show the difference in the inputs boxes below.
Engagement should be the time difference between Page Time and Ack Time;
Arrival should be the time difference between Ack Time and Arrival Time;
Investigation should be the time difference between Arrival and Start Replace Time;
Mitigate should be the time difference between Start Replace and Replaced time;
Total Ops Phases should be the time difference between Replaced and Page time.
I'm stuck on the code above for almost 8 hours, changed a lot of things trying to do the math and put each time difference inside an array and then use it to fill the inputs, but it seems the array isn't get filled with data.
Unfortunately I have to use the seconds as well, and I couldn't find much material with different solutions to calculate the difference of times using it.
I will be glad if someone can see another way to solve this matter.
Thanks in advance!
PS: Tried to insert a print of the form but I don't have the reputation needed.

The type="time" attribute is only supported by chrome, not Firefox or Internet Explorer so you should be using a compatibility library like these or one of your own making. If you just want to use chrome you can use valueAsNumber:
v.valueAsNumber
56013000
v.valueAsDate
Thu Jan 01 1970 10:33:33 GMT-0500 (EST)
v.value
"15:33:33"
Note that the Chrome console will show you these options with auto suggest.
Also jsfiddle

Related

Changes in time picker should also changes the time input field

I've got this code to show the total minutes in an input field. I would like to have changes in it whenever a user picks a different time in the time picker and the time in the input field also changes. How would I get that goal? This is the code I used:
const getSeconds = s => s.split(":").reduce((acc, curr) => acc * 60 + +curr, 0);
var seconds1 = getSeconds(document.getElementById("stime").value);
var seconds2 = getSeconds(document.getElementById("etime").value);
var res = Math.abs(seconds2 - seconds1);
var hours = Math.floor(res / 3600);
var minutes = Math.floor(res % 3600 / 60);
var seconds = res % 60;
document.getElementById("time").value = seconds;
<div>
<div class="form-floating">
<input id="stime" class="form-control" required name="stime" type="time" value="12:00" />
<label for="stime">Start Time</label>
</div>
</div>
<div>
<div class="form-floating">
<input id="etime" class="form-control" required name="etime" type="time" value="12:30" />
<label for="etime">End Time</label>
</div>
</div>
<div>
<div class="form-floating">
<input id="time" class="form-control" name="time" type="text" />
<label for="time">Time</label>
</div>
</div>
This is how image looks like...
The best practice is to move the calculation parts of your code into a function and call that function once the page is loaded and when any change is made to the inputs.
const getSeconds = s => s.split(":").reduce((acc, curr) => acc * 60 + +curr, 0);
const twoDigit = s => s < 10 ? '0'+s : s;
const timeToMins = s => s.split(':')[0]*60 + +s.split(':')[1];
const formatTime = s => {
let hours = Math.floor(s / 60);
let minutes = Math.floor(s % 60);
return `${twoDigit(hours)}:${twoDigit(minutes)}`
}
const updateInput = () => {
let start = getSeconds(document.getElementById("stime").value);
let end = getSeconds(document.getElementById("etime").value);
let res = Math.abs(end - start);
let diff = formatTime(res)
document.getElementById("time").value = diff;
}
const updateEnd = () => {
let start = getSeconds(document.getElementById("stime").value);
let diff = document.getElementById("time").value
let end = formatTime(start+timeToMins(diff))
document.getElementById("etime").value = end;
}
updateInput()
<div>
<div class="form-floating">
<input id="stime" onchange="updateInput()" class="form-control" required name="stime" type="time" value="12:00" />
<label for="stime">Start Time</label>
</div>
</div>
<div>
<div class="form-floating">
<input id="etime" onchange="updateInput()" class="form-control" required name="etime" type="time" value="12:30" />
<label for="etime">End Time</label>
</div>
</div>
<div>
<div class="form-floating">
<input id="time" onkeyup="updateEnd()" class="form-control" name="time" type="text" />
<label for="time">Time Difference</label>
</div>
</div>
These are the codes I have so far for this.
const getSeconds = s => s.split(":").reduce((acc, curr) => acc * 60 + +curr, 0);
var seconds1 = getSeconds(document.getElementById("stime").value);
var seconds2 = getSeconds(document.getElementById("etime").value);
var res = Math.abs(seconds2 - seconds1);
var hours = Math.floor(res / 3600);
var minutes = Math.floor(res % 3600 / 60);
var seconds = res % 60;
document.getElementById("time").value = seconds;
<div>
<div class="form-floating">
<input id="stime" class="form-control" required name="stime" type="time" value="12:00" />
<label for="stime">Start Time</label>
</div>
</div>
<div>
<div class="form-floating">
<input id="etime" class="form-control" required name="etime" type="time" value="12:30" />
<label for="etime">End Time</label>
</div>
</div>
<div>
<div class="form-floating">
<input id="time" class="form-control" name="time" type="text" />
<label for="time">Time</label>
</div>
</div>

get total sum of minutes between 2 fields

im trying to get the total minutes from this 2 fields but i keep getting the 60 minutes results but wont show more even when there is few hours in between.
sample
01:59 04:59 getting result 60 minutes
01:59 04:59 wanted result 299 minutes
$(document).ready(function () {
if ($('#duration').val() === '') {
updateDuration($('#start_time').val(), $('#end_time').val());
}
$('#start_time').on('change keyup', function () {
updateDuration($('#start_time').val(), $('#end_time').val());
});
$('#end_time').on('change keyup', function () {
updateDuration($('#start_time').val(), $('#end_time').val());
});
function updateDuration(startTime, endTime) {
var ms = moment(endTime, ' HH:mm:ss').diff(moment(startTime, 'HH:mm:ss')),
dt = moment.duration(ms),
h = Math.floor(dt.asHours()),
m = moment.utc(ms).format('mm');
$('#duration').val('' + m + ' minutes');
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="http://cdnjs.cloudflare.com/ajax/libs/moment.js/2.5.1/moment.min.js"></script>
<p>
<label for="start_time">Start Time</label>
<br>
<input id="start_time" name="start_time" type="text" value="00:00">
</p>
<p>
<label for="end_time">End Time</label>
<br>
<input id="end_time" name="end_time" type="text" value="15:53">
</p>
<p>
<label for="duration">Duration</label>
<br>
<input id="duration" name="duration" type="text">
</p>
Here's one way to do it without moment. Just convert everything to seconds and subtract. If the endtime is less than the start time, we add 24 hours to the end.
$(document).ready(function() {
$('#start_time, #end_time').on('keyup', function() {
updateDuration($('#start_time').val(), $('#end_time').val());
});
$('#start_time').trigger('keyup')
});
const getSeconds = t => t.split(":").reduce((b, a, i) => b + (+a * (i === 0 ? 60 : 1)),0);
function updateDuration(startTime, endTime) {
let start = getSeconds(startTime),
end = getSeconds(endTime)
if (end < start) end += (24 * 60 )
let result = end - start
let m = Math.floor(result/60), s = Math.floor((result%60))
$('#duration').val(`${m} minutes, ${s} seconds`);
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="http://cdnjs.cloudflare.com/ajax/libs/moment.js/2.5.1/moment.min.js"></script>
<p>
<label for="start_time">Start Time</label>
<br>
<input id="start_time" name="start_time" type="text" value="23:59">
</p>
<p>
<label for="end_time">End Time</label>
<br>
<input id="end_time" name="end_time" type="text" value="15:53">
</p>
<p>
<label for="duration">Duration</label>
<br>
<input id="duration" name="duration" type="text">
</p>

Adding Military Time - Textbox for HH and Texbox for MM?

I've been able to get this working GREAT when using a single textbox that has the HH:MM split with :, but when the HH are in a separate textbox from MM I'm completely lost. I'm needing to calculate time worked from the time entered and then outputted to the decimal format then minus the lunch. Any help would be awesome!
// adding military time
$(function () {
function calculate () {
var time1 = $("#element_33_1").val(), time1_1 = $("#element_33_2").val(), time2 = $("#element_34_1").val(), time2_1 = $("#element_34_2").val();
var hours1 = (time1),
hours2 = (time2),
mins1 = (time1_1),
mins2 = (time2_1);
var hours = hours2 - hours1, mins = 0;
if(hours <= 0) hours = 0 + hours;
if(mins2 >= mins1) {
mins = mins2 - mins1;
}
else {
mins = (mins2 + 60) - mins1;
hours--;
}
mins = mins / 60; // take percentage in 60
hours += mins;
hours = hours.toFixed(2);
$("#element_509").val(hours);
}
$("#element_33_1,#element_33_2,#element_34_1,#element_34_2").keyup(calculate);
calculate();
});
//Hours Billed Total
$(document).ready(function() {
$("#element_29,#element_509,#element_33_1,#element_33_2,#element_34_1,#element_34_2,#element_39").keyup(function(ev){
var val1=parseFloat($("#element_509").val());
var val2=parseFloat($("#element_39").val());
$("#element_29").val((val1 - val2).toFixed(2));
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<li id="li_33" class="time_field column_4">
<fieldset>
<legend style="display: none">Start Time</legend>
<span class="description">Start Time <span id="required_33" class="required">*</span></span>
<span>
<input id="element_33_1" name="element_33_1" class="element text " size="2" type="text" maxlength="2" value="" />
<label for="element_33_1">HH</label>
</span>
<span>
<input id="element_33_2" name="element_33_2" class="element text " size="2" type="text" maxlength="2" value="" />
<label for="element_33_2">MM</label>
</span>
</fieldset>
</li> <li id="li_39" class="column_4 guidelines_bottom">
<label class="description" for="element_39">Lunch Hour <span id="required_39" class="required">*</span></label>
<div>
<input id="element_39" name="element_39" class="element text medium" type="text" value="" />
</div>
</li> <li id="li_34" class="time_field column_4">
<fieldset>
<legend style="display: none">Stop Time</legend>
<span class="description">Stop Time <span id="required_34" class="required">*</span></span>
<span>
<input id="element_34_1" name="element_34_1" class="element text " size="2" type="text" maxlength="2" value="" />
<label for="element_34_1">HH</label>
</span>
<span>
<input id="element_34_2" name="element_34_2" class="element text " size="2" type="text" maxlength="2" value="" />
<label for="element_34_2">MM</label>
</span>
</fieldset>
<input id="element_509" value="" name="Subtotal"/>
</li> <li id="li_29" class="column_4">
<label class="description" for="element_29">Hours Billed <span id="required_29" class="required">*</span></label>
<div>
<input id="element_29" name="element_29" class="element text medium" type="text" data-quantity_link="element_44" value="" />
</div>
You definitely want to convert to a common unit (minutes) first.
It looks like you're attempting that with:
mins = mins / 60
but that's not correct.
{correction: it is technically correct, but you could potentially lose/gain time when converting back to your billing units. See the additional info below.}
You want something like:
var totalMinutes = mins + (hours * 60);
Also, fix the typo on line 7:
time2_1 = $("#element_33_2").val();
Should be:
time2_1 = $("#element_34_2").val();
Added:
To hide the NaNs and negative values, you could test the vars before assigning to val and also clear previous results if there are errors:
var val3 = (val1 - val2).toFixed(2);
if (isNaN(val3) || val3 < 0)
{
$("#element_29").val("");
}
else
{
$("#element_29").val(val3);
}
I would still recommend working with minutes-as-integers rather than hours-as-floats. The comments on this question have some good info on time reporting.

JS/jQuery: fire onchange from a disabled/readonly input without using button

The goal is to get the total Qty for the whole year.
The user will input numbers into 3 different textboxes(Jan,Feb,Mar), then the sum will be displayed into a disabled textbox(Quarter1).
Now I have 4 instances of these knowing we have 4 quarters/year.
I can easily display the sum per quarter, by using the onchange() function attached to the textboxes.
Now I am having issues getting the sum from the 4 disabled textboxes, knowing we can't use the onchange() on it because it's disabled.
I have searched and probably getting results only when a button is used.
TLDR: I am trying to display the sum from the four disabled textboxes to another textbox automatically, without the user clicking any button(just like firing the onchange event)
I have tried this one, wherein I tried to display the value of the first quarter to the total, and not working:
$(document).ready(function() {
$('input[id$=yearlyTotal]').bind("displaytotal", function() {});
$('#qtr1').change(function() {
var mos = document.getElementsByClassName("quantityA");
var mosCount = mos.length;
var total = 0;
for (var i = 0; i < mosCount; i++) {
total = total + parseInt(mos[i].value);
}
$('input[id$=yearlyTotal]').val(total).trigger('displaytotal');
});
});
Hope it's possible, thanks in advance
EDIT: Added UI
Showing Q1 (its just the same for the 4 qtrs)
<div class="form-group col-md-6">
<label class="col-sm-1 control-label">Jan:</label>
<div class="col-sm-2 small">
<input type="number" min="0" id="col3" class="form-control input-sm monthly" data-q="q1" name="January" />
</div>
<label class="col-sm-1 control-label">Feb:</label>
<div class="col-sm-2 small">
<input type="number" min="0" id="col4" class="form-control input-sm monthly" data-q="q1" name="February" />
</div>
<label class="col-sm-1 control-label">Mar:</label>
<div class="col-sm-2 small">
<input type="number" min="0" id="col5" class="form-control input-sm monthly" data-q="q1" name="March" />
</div>
<label class="col-sm-1 control-label">Q1:</label>
<div class="col-sm-2 small">
<input type="text" min="0" id="q1" class="form-control input-sm quarter" name="q1" style="background-color: #b3dcf5;" disabled />
</div>
</div>
This is the div for the total Qty
<div class="col-md-6">
<label class="col-sm-3 control-label" id="">Total Quantity:</label>
<div class="col-sm-3 small">
<input type="text" id="final" class="form-control input-sm" name="TotalQuantity" value="0" disabled />
</div>
</div>
Method 1:
Basically, what you need to do is to trigger the change event for the disabled quarter fields programatically, using jQuery .trigger() function.
As I don't know how your HTML is structured -this why it is always recommended to provide MCVE example- I made a demo example and I've done things differently, like below:
jsFiddle 1
var monthly = $('.monthly'),
Qrt = $('.quarter');
monthly.on('change, input', function() {
var $th = $(this),
// depending on the value of the data-q attribute, we pick
// all input fields with the same data-q as an array, then
//loop through them adding their values up
q = $th.attr('data-q'),
qArray = $th.parent().children('input[data-q="' + q + '"]'),
tempSum = 0;
for (var i = 0, ln = qArray.length; i < ln; i++) {
tempSum += +$(qArray[i]).val();
}
// we pick the corresponding quarter sum field, again depending
// on the value of the data-q attritues, and update its value, then
// we trigger the change event of this quarter sum field.
$('#' + q).val(tempSum).trigger('change'); // here you trigger it
});
Qrt.on('change', function() {
var qSum = 0;
for (var i = 0, ln = Qrt.length; i < ln; i++) {
qSum += +$(Qrt[i]).val();
}
$('#final').val(qSum);
});
.monthly { width: 32%; }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
<h3>Grand Total:</h3><input type="text" id="final" disabled><hr>
<h3>1st Q:</h3>
<input type="text" class="monthly" data-q="q1">
<input type="text" class="monthly" data-q="q1">
<input type="text" class="monthly" data-q="q1">
<br>Sum:<input id="q1" type="text" class="quarter" disabled>
<h3>2nd Q:</h3>
<input type="text" class="monthly" data-q="q2">
<input type="text" class="monthly" data-q="q2">
<input type="text" class="monthly" data-q="q2">
<br>Sum:<input id="q2" type="text" class="quarter" disabled>
<h3>3rd Q:</h3>
<input type="text" class="monthly" data-q="q3">
<input type="text" class="monthly" data-q="q3">
<input type="text" class="monthly" data-q="q3">
<br>Sum:<input id="q3" type="text" class="quarter" disabled>
<h3>4th Q:</h3>
<input type="text" class="monthly" data-q="q4">
<input type="text" class="monthly q-4th" data-q="q4">
<input type="text" class="monthly q-4th" data-q="q4">
<br>Sum:<input id="q4" type="text" class="quarter" disabled>
Method 2:
since any change you make to any .monthly field will change the corresponding value of quarter sum, and thus it'll also affect the value of the yearly sum, you don't need to capture the change event of the disabled quarter sum fields, just loop through their values and update the value of the yearly field, all should be done inside the on('change') event of the .monthly fields, like below:
jsFiddle 2
jQuery
var monthly = $('.monthly'),
Qrt = $('.quarter');
monthly.on('change, input', function() {
var $th = $(this),
q = $th.attr('data-q'),
qArray = $th.parent().children('input[data-q="' +q+ '"]'),
tempSum = 0,
qSum = 0;
for (var i = 0, ln = qArray.length; i < ln; i++) {
tempSum += +$(qArray[i]).val();
}
$('#' + q).val(tempSum);
// code below
for (var i = 0, ln = Qrt.length; i < ln; i++) {
qSum += +$(Qrt[i]).val();
}
$('#final').val(qSum);
});
Update:
For the updated HTML in the OP, replace qArray line with this one:
$th.parents('.form-group').find('input[data-q="' + q + '"]')`,
Note parents() is with "s" letter, unlike the former parent() which moves up a single level up the DOM, it does " search through the ancestors of these elements in the DOM tree and construct a new jQuery object from the matching elements ordered from immediate parent on up. ", so it travels up until we reach the matchng parent, here it is .form-group.
Then instead of children(), we use find().
jsFiddle 3
Please find the below code (Finding the total for quarter A & quarter B) for your reference. Please use same methodology for other quarters.
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script>
$(document).ready(function(){
/* FINDING THE QUARTER A AND QUARTER B */
function findingQuaterTotal () {
/* LOADING QUARTER A AND FINDING ITS TOTAL - STARTS */
var mosQuarterA = document.getElementsByClassName("quarterA"),
mosCountQuarterA = mosQuarterA.length,
totalQuarterA = 0,
i = 0;
for (i = 0; i < mosCountQuarterA; i++) {
totalQuarterA = totalQuarterA + parseInt(mosQuarterA[i].value);
}
/* ADDING INTO QUATER A DISABLED TEXTBOX */
$("#quarterA").val(totalQuarterA);
/* LOADING QUARTER A AND FINDING ITS TOTAL - ENDS */
/* LOADING QUARTER B AND FINDING ITS TOTAL - STARTS */
var mosQuarterB = document.getElementsByClassName("quarterB"),
mosCountQuarterB = mosQuarterB.length,
totalQuarterB = 0;
for (i = 0; i < mosCountQuarterB; i++) {
totalQuarterB = totalQuarterB + parseInt(mosQuarterB[i].value);
}
/* ADDING INTO QUARTER B DISABLED TEXTBOX */
$("#quarterB").val(totalQuarterB);
/* LOADING QUARTER B AND FINDING ITS TOTAL - ENDS */
/* TRIGGERING CHANGE EVENT IN THE DISABLED TEXTBOX WHOSE ID STARTS WITH QUARTER.*/
$("input[id^='quarter']").trigger("change");
};
/* ABOVE CHANGE TRIGGER WILL CALL BELOW EVENTS - STARTS */
$("input[id^='quarter']").change(function () { $("#final").val(parseInt($("#quarterA").val())+parseInt($("#quarterB").val()));
});
/* ABOVE CHANGE TRIGGER WILL CALL BELOW EVENTS - ENDS */
/* IF ANY VALUE CHANGES IN MONTH TEXT BOX, FLLWING FUNCTION WILL BE CALLED - STARTS */
$("input[id^='month']").on("change keyup",function () {
findingQuaterTotal();
});
findingQuaterTotal();
/* IF ANY VALUE CHANGES IN MONTH TEXT BOX, FLLWING FUNCTION WILL BE CALLED - ENDS */
});
</script>
</head>
<body>
<h2>Quater A</h2>
Jan - <input type="number" id="month1" value="6" class="quarterA"></br>
Feb - <input type="number" id="month2" value="16" class="quarterA"></br>
March - <input type="number" id="month3" value="25" class="quarterA"></br>
Quater A Total - <input type="number" id="quarterA" value="" disabled></br>
<br/><br/>
<h2>Quater B</h2>
April - <input type="number" id="month4" value="6" class="quarterB"></br>
May - <input type="number" id="month5" value="16" class="quarterB"></br>
June - <input type="number" id="month6" value="25" class="quarterB"></br>
Quater B Total - <input type="number" id="quarterB" value="" disabled></br>
Quarter A and Quarter B total - <input type="number" id="final" value="" disabled>
</body>
</html>

AngularJS : how to properly use Math.pow in filters

I'm new to AngularJs & still learning JS and not skilled in maths so please, be gentle :)
I'm trying to make a loan calulator for a mobile app for my company.
I would like to make one which can auto-refresh the result when a value is change to get rid of the "result/ calculate" button.
I take a look at Angular filters, it's pretty easy to build a simple math formula, but exponent values give me headache...
I've find on Stackoverflow how to use a filter to use Math.pow with Angular Filters, but i just can't resolve the formula...
This is the formula i have to build :
m = Monthly payment
K = Kapital
R = Rate %
n = Period of payement, in years
m = [( K * R ) / 12] / [ 1 - ( 1 + ( R / 12 )) ^-n]
For 1000000 capital, 60 years and 5% rate, the answer should be 4386.42
var app = angular.module('app', []);
function Ctrl($scope) {
$scope.Math = window.Math;
};
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="app">
<div ng-controller="Ctrl">
<form>
<div class="item">
<label>Capital</label>
<input type="range" id="loan" name="loan" ng-model="capital" min="10000" max="1000000" step="10000" value="10000">
<h1>{{capital}}</h1>
</div>
<hr>
<div class="item">
<label>Number of years</label>
<input type="range" id="duree" name="duree" ng-model="time" min="0" max="60" step="5" value="1">
<h1>{{time}}</h1>
</div>
<hr>
<div class="item">
<label>rate %</label>
<input type="range" id="duree" name="rate" ng-model="rate" min="1" max="15" step="0.1" value="1">
<h1>{{rate}}</h1>
</div>
<div class="item">
<h1>Monthly payment : {{((capital * (rate /1200) * (time / 12))/12) + (capital / time) | number:2 }}</h1>
<h2 >
</h2>
</div>
</form>
</div>
</div>
A jsFiddle demo here :
http://jsfiddle.net/_Arn__/nruqk9z8/5/
Could someone help me on this, please ?
Regards,
Arno
I think n should be months (n*12):
//m = Monthly payment
//K = Kapital
//R = Rate %
//n = Period of payement, in years
var m ;
var K = 1000000;
var R = 0.05;
var n = 60*12;
var dnmntr = ( 1 + ( R / 12 ));
var nmrtr = ( K * R )/12;
m = nmrtr / (1-Math.pow(dnmntr,-n));
console.log(m);
Prints: 4386.418998606701

Categories

Resources