How Resolve Currency IDR in javascript - javascript

How can resolve script like this ?
for example count or minus Variable A and Variable B in currency IDR
thanks, anyone can help me ...
<html>
<head>
<meta http-equiv="Content-Language" content="en-us">
<meta http-equiv="Content-Type" content="text/html; charset=windows-1252">
<title>New Page 1</title>
</head>
<body>
<form name="form1">
<input id="harga" onkeyup="formatangka_titik()" type="text" />
<input id="diskon" onkeyup="formatangka_titik()" type="text" />
<input id="bayar" onkeyup="formatangka_titik()" type="text" />
</form>
</body>
</html>
here code javascript function :
<script type="text/javascript">
function formatangka_titik()
{
a = form1.harga.value;
b = a.replace(/[^\d]/g,"");
c = "";
panjang = b.length;
j = 0;
for (i = panjang; i > 0; i--)
{
j = j + 1;
if (((j % 3) == 1) && (j != 1))
{
c = b.substr(i-1,1) + "." + c;
} else {
c = b.substr(i-1,1) + c;
}
}
form1.harga.value = c;
</script>

I think your problem is that you are adding two strings together, which will concatenate the strings instead of add the numeric values.
Example adding string types:
var a = '1';
var b = '2';
console.log(a + b); // prints '12' to the console
Example adding int types:
var a = 1;
var b = 2;
console.log(a + b); // prints '3' to the console
JavaScript is loosely typed, so it's not always immediately apparent what a variable's type is.
You can do a few things to change a string-type variable to an int.
Here are a couple common ways:
var stringNum = '123';
var intNum1 = parseInt(stringNum, 10);
var intNum2 = +stringNum;
Specifically, your code would need to look something like this:
function formatangka_titik() {
var a = form1.harga.value.replace(/[^\d]/g, "");
var b = form1.diskon.value.replace(/[^\d]/g, "");
var a = +a; // converts 'a' from a string to an int
var b = +b; // converts 'b' from a string to an int
form1.harga.value = formatNum(a);
form1.diskon.value = formatNum(b);
form1.bayar.value = formatNum(+a + b);
}
function formatNum(rawNum) {
rawNum = "" + rawNum; // converts the given number back to a string
var retNum = "";
var j = 0;
for (var i = rawNum.length; i > 0; i--) {
j++;
if (((j % 3) == 1) && (j != 1))
retNum = rawNum.substr(i - 1, 1) + "." + retNum;
else
retNum = rawNum.substr(i - 1, 1) + retNum;
}
return retNum;
}
<form name="form1">
<input id="harga" onkeyup="formatangka_titik()" type="text" />
<input id="diskon" onkeyup="formatangka_titik()" type="text" />
<input id="bayar" onkeyup="formatangka_titik()" type="text" />
</form>

In above example how we can calculate percentage for IDR currency.

Related

Is there a way to split inserted value for example 1234567890 to 12345 and 67890?

Is there a function that splits the the given string into 2 evenly and place half of each to different textboxes?
I have tried var.split and var.slice
<script>
function display()
{
var myStr = document.getElementbyId("reqnum").value;
var strArray = myStr.split(" ");
// Display array values on page
for(var i = 0; i < strArray.length; i++){
document.write("<p>" + strArray[i] + "</p>");
}
}
the expected should split the no. evenly and would display an error if the numbers are odd.
You can check the length of your input string. If it is odd then display an error.
<input type="text" id="reqnum" >
<input type="button" value="Display" onclick="display()">
<script>
function display()
{
var myStr = document.getElementById("reqnum").value;
if( !myStr || myStr.length % 2 == 1){
document.write("<p>Invalid input</p>");
}else{
var a = parseInt(myStr.substring(0, myStr.length/2));
var b = parseInt(myStr.substring(myStr.length/2, myStr.length));
document.write("<p>" + a + "</p>");
document.write("<p>" + b + "</p>");
document.write("<p> Result after multiplication : " + (a*b) + "</p>");
}
}
</script>
you can convert the numbers to string and then you can do the following.
var num = "1234567890"
var num1
var num2
if (num.length % 2 == 0) {
num1 = num.slice(0, (num.length / 2))
num2 = num.slice((num.length / 2))
} else {
console.log("Number contains odd number of digits")
}
console.log("Num1 " + num1 + " and Num2 " + num2)
use the Slice method, documentation is here.
For your slicing in half:
let half1, half2;
if( myStr.length % 2 == 0 ){
half1 = myStr.slice(0, (myStr.length / 2));
half2 = myStr.slice( (myStr.length / 2), myStr.length );
} else {
// error code
}
function splitToEqual(num){
num = num.toString()
return [num.substring(0, num.length / 2), num.substring(num.length / 2, num.length)]
}
console.log(splitToEqual(1234567890))
Have you tried using slice and length String methods?
Ie.
const string = '1234567890';
const length = string.length;
const res1 = string.slice(0,length/2);
const res2 = string.slice(length/2);
console.log(res1,res2);
Based on your request, I created the following piece of code :-)
Hope it helps.
var inputBox, warning, fBox, sBox;
function inputBoxChanged(e) {
var text = e.currentTarget.value;
if (text.length % 2 != 0) {
warning.innerText = "Value needs to be even sized";
fBox.value = "";
sBox.value = "";
} else {
warning.innerText = "";
var splitPos = text.length / 2;
fBox.value = text.slice(0, splitPos);
sBox.value = text.slice(splitPos, text.length);
}
}
document.addEventListener("DOMContentLoaded", function (e) {
inputBox = document.getElementById("input");
warning = document.getElementById("warning");
fBox = document.getElementById("first");
sBox = document.getElementById("second");
inputBox.addEventListener("change", inputBoxChanged);
});
<html>
<body>
<input id="input" type="text"/>
<span id="warning"></span>
<hr/>
<input id="first" type="text" readonly/>
<input id="second" type="text"readonly/>
</body>
</html>
Use substring() function as
var substring=string.substring(strating_index,end_index);
index will start from 0
var str="1234567890"
var substr=str.substring(0,str.length/2);
var substr2=str.substring(strlength/2,strlength);
$("#ID1").val(substr);
$('#ID2').val(substr2);

Loop for issue javascript won't run

So this exercice is about outputing a word by the number typed in the input section simple but i find this problem the loop for won't work if there is any help i will be greatfull
<head>
<meta charset="utf-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<script defer>
function Verifer() {
var ch = document.querySelector("input").value
var nbr = document.getElementById("nb").value
if ((nbr > 0) && (ch != "")) {
for (let i = 1; i >= nbr; i++) {
var txt = ""
txt += "<h1>" + ch + "</h1> <br>"
document.getElementById("d2").innerHTML = txt
}
} else {
alert("Retype plz")
}
}
</script>
</head>
<body>
// the first input is to type a String //the seconde input to type the number of repetition of this String
<strong>Chain :</strong><input type="text" id="chain" maxlength="20"><br>
<strong>nombre de rep :</strong><input type="number" maxlength="5" id="nb"><br>
<button type="button" onclick="Verifer()">Envoyer</button>
<div id="d2">
//This part is dedicated to the output of the function
</div>
</body>
change
var nbr = document.getElementById("nb").value
to
var nbr = parseInt(document.getElementById("nb").value)
Is this what you want to do? Your question is a bit vague.
function Verifer() {
var ch = document.querySelector("input").value;
var nbr = document.getElementById("nb").value;
nbr = parseInt(nbr); //Parse to int
console.log(nbr);
if (nbr === NaN || !ch) { //Validate
document.getElementById("nb").value = "invalid";
return;
}
var txt = ""; //Set var in scope around for loop
for (var i = 1; i <= nbr; i++) { //repeat when i is less or equal to nbr
txt += "<h1>" + ch + "</h1> <br>" //Append txt
}
document.getElementById("d2").innerHTML = txt; //Add txt to element html
}
<strong>Chain :</strong><input type="text" id="chain" maxlength="20"><br>
<strong>nombre de rep :</strong><input type="number" maxlength="5" id="nb"><br>
<button type="button" onclick="Verifer()">Envoyer</button>
<div id="d2">
</div>

How to show the numbers in indian format in html

I am having an input type of number when the user types a number it should be displayed in indian format that is
Example: 500000 should be displayed as 50,000
Without using javascript how could i use the indian format in the html itself.
I have already used the filters to show the values in indian format which works well for viewing the data but i would like to do the same during input also but when i tried using the same filter in the model it doesn;t show anything.
Html:
<input ng-if="vm.farmer.type === 'Advance'"
type="number" maxlength="9" placeholder="{{'advamount_message' | translate}}" step=".01"
ng-model="vm.advance.amount_out" ng-change="vm.fillStarted()"
next-focus id="field1"
field-to-validate="yes"
field-value="{{vm.advance.amount_out}}" field-validation-type="num" field-name="{{'vamount_message' | translate}}">
Filter used for view:
.filter('INR', function () {
return function (input) {
if (!isNaN(input)) {
//var currencySymbol = '₹';
/*var result = input.toString().split('.');
var lastThree = result[0].substring(result[0].length - 3);
var otherNumbers = result[0].substring(0, result[0].length - 3);
if (otherNumbers !== '') {
lastThree = ',' + lastThree;
}
var output = otherNumbers.replace(/\B(?=(\d{2})+(?!\d))/g, ',') + lastThree;
// var output = otherNumbers.replace(/(\d)(?=(\d\d)+\d$)/g, ',') + lastThree;
if (result.length > 1) {
output += '.' + result[1];
}
return output;*/
var negative = input < 0;
var str = negative ? String(-input) : String(input);
var arr = [];
var i = str.indexOf('.');
if (i === -1) {
i = str.length;
} else {
for (var j = str.length - 1; j > i; j--) {
arr.push(str[j]);
}
arr.push('.');
}
i--;
for (var n = 0; i >= 0; i--, n++) {
if (n > 2 && (n % 2 === 1)) {
arr.push(',');
}
arr.push(str[i]);
}
if (negative) {
arr.push('-');
}
return arr.reverse().join('');
}
};
During view:
{{vm.farmer.balance | INR}}
Try this filter
<!DOCTYPE html>
<html>
<head>
<title></title>
<meta charset="utf-8" />
</head>
<body>
<div ng-app="app" ng-controller="ctrl">
{{price | INR}}
</div>
<script src="../lib/angular.js"></script>
<script>
var app = angular.module('app', []);
app.filter('INR', function () {
return function (input) {
var length = input.length;
if(input.length < 3)
{
return input;
}
else {
var input = input.split(''); //convert it to string and split it into the chars
var output = input[length - 3] + input[length - 2] + input[length - 1];
var j = 2;
for(i=input.length;i--;i>1)
{
if(j>1)
{
output = ',' + output;
j = 0;
}
else {
}
if (i != 0)
{
output = input[i - 1] + output;
j++;
}
}
return output;
}
}
});
app.controller('ctrl', function ($scope) {
$scope.price = '4665987565';
});
</script>
</body>
</html>
you can use this :-
In HTML Template Binding
{{ currency_expression | currency : symbol : fractionSize}}
In JavaScript
$filter('currency')(amount, symbol, fractionSize)
<script>
angular.module('currencyExample', [])
.controller('ExampleController', ['$scope', function($scope) {
$scope.amount = 1234.56;
}]);
</script>
<div ng-controller="ExampleController">
<input type="number" ng-model="amount" aria-label="amount"> <br>
default currency symbol ($): <span id="currency-default">{{amount | currency}}</span><br>
custom currency identifier (USD$): <span id="currency-custom">{{amount | currency:"USD$"}}</span><br>
no fractions (0): <span id="currency-no-fractions">{{amount | currency:"USD$":0}}</span>
</div>

Nth Fibonacci Term JavaScript *New to JS*

<!DOCTYPE HTML>
<html>
<title>Fibonacci Assignment</title>
<head>
<script>
function chkInput(){
var n = parseInt(n1)
var a,b,r;
a = 0;
b = 1;
r = 1;
for(var i = 2; i <= n; i++){
r = a + b;
a = b;
b = r;
}
alert (r);
}
</script>
</head>
<body>
<input type="text"
id="n1">
<input type="button"
value="Enter"
onclick="chkInput(n1.value)">
</body>
</html>
I'm new to JavaScript and I've been attempting to construct a code for finding the Nth term of the Fibonacci Sequence where the User inputs a number and the sequence runs until the nth number. I have been tasked with using both a function and a for loop for this. However when I run it, no matter what number I input it returns as 1. My questions is why that might be? I'm a student so I just need general direction not the answer. This snippet is what I have so far.
You weren't capturing the text input value as a parameter.
You had:
checkInput()
It should be
chkInput(n1)
So your line
var n = parseInt(n1);
Was parsing undefined, so the value of n is now NAN (Not a Number), so the for loop never got executed.
function chkInput(n1) {
var n = parseInt(n1);
var a, b, r;
a = 0;
b = 1;
r = 1;
for (var i = 2; i <= n; i++) {
r = a + b;
a = b;
b = r;
}
alert(r);
}
<input type="text" id="n1">
<input type="button" value="Enter" onclick="chkInput(n1.value)">
You have almost done with your assignment.
You have missed to receive the value in the function definition.
Altering function chkInput(){ to function chkInput(n1){ will complete your assignment.
Find the your working code snippet below.
<!DOCTYPE HTML>
<html>
<title>Fibonacci Assignment</title>
<head>
<script>
function chkInput(inputValue) {
var n = parseInt(inputValue)
var a,b,r;
a = 0;
b = 1;
r = 1;
for(var i = 2; i <= n; i++){
r = a + b;
a = b;
b = r;
}
alert (r);
}
</script>
</head>
<body>
<input type="text" id="n1">
<input type="button" value="Enter" onclick="chkInput(n1.value)">
</body>
</html>
You need to get value of element using DOM functions like document.getElementById("n1").value
Also your algorithm is wrong it should have a = 1;
function chkInput(){
var n = parseInt(document.getElementById("n1").value)
var a,b,r;
a = 1;
b = 1;
r = 1;
for(var i = 2; i <= n; i++){
r = a + b;
a = b;
b = r;
}
alert (r);
}
<!DOCTYPE HTML>
<html>
<title>Fibonacci Assignment</title>
<head>
<script>
</script>
</head>
<body>
<input type="text"
id="n1">
<input type="button"
value="Enter"
onclick="chkInput(n1.value)">
</body>
</html>

functions inside a class

We need to make a class called Series with two methods
triNums - function that returns you a triangular series by the number it recives eg: if the function gets 5 - 1, 3, 6, 10, 15
fibNums - function that returns you a fibonacci sequence by the number it
recives eg: if the function gets 5 - 0,1,1,2,3,5
Each of the functions need to be executed when pressing on a button (fibo)(tri) and each element of the result should be displayed on a button
class Series {
tri() {
const num = document.querySelector("#num").value
if (num) {
addBtns(triNums(num));
}
}
addBtns(arr) {
const feed = document.querySelector("#feed");
var btns = ""; //no buttons by default
for (let v of arr) { //iterate over all values
btns += "<button>" + v + "</button>";
}
feed.innerHTML = btns;
}
triNums(num) {
var triNums = [];
for (let n = 0; n < num.value; n++) {
triNums[n] = n * (n + 1) / 2;
}
return triNums;
}
triNum(n) {
return (n * (n + 1) / 2);
}
}
<!DOCTYPE HTML>
<html lang="en-US">
<head>
<meta charset="UTF-8" />
<title></title>
<script src="home6617.js"></script>
</head>
<body>
Enter Name <input id="name" placeholder="Enter name"></input>
<button onclick="sayHello()">Click me</button>
<h1 id="hello"></h1>
<input id="num"></input>
<button onclick="tri()">triangular</button>
<div id="feed"></div>
</body>
</html>
You made some mistakes:
you pass #num.value to triNums, which is a Number, and then you try to access its value, which is unneccessary and impossible.
You cannot call tri() as it is part of a Series instance. You could do (new Series).tri() .
Same applies for inner function calls, you must access them via this :
class Series {
tri() {
const num = document.querySelector("#num").value
if (num) {
this.addBtns(this.triNums(num));
}
}
addBtns(arr) {
const feed = document.querySelector("#feed");
var btns = ""; //no buttons by default
for (let v of arr) { //iterate over all values
btns += "<button>" + v + "</button>";
}
feed.innerHTML = btns;
}
triNums(num) {
var triNums = [];
for (let n = 0; n < num; n++) {
triNums[n] = n * (n + 1) / 2;
}
return triNums;
}
triNum(n) {
return (n * (n + 1) / 2);
}
}
function start(){
(new Series).tri();
}
<!DOCTYPE HTML>
<html lang="en-US">
<head>
<meta charset="UTF-8" />
<title></title>
<script src="home6617.js"></script>
</head>
<body>
<div id="feed"></div>
<input id="num" />
<button onclick="start()">Start</button>
</body>
</html>

Categories

Resources