How to use Formatting for large numbers - javascript

I have a large number issue here. I'm using the nFormatter for large numbers in javascript but i have no idea how to use it with my existing code.
Here is the formatter im using.
function nFormatter(num) {
if (num >= 1000000000000) {
return (num / 1000000000000).toFixed(1).replace(/\.0$/, '') + 'Trillion';
}
if (num >= 1000000000) {
return (num / 1000000000).toFixed(1).replace(/\.0$/, '') + 'Billion';
}
if (num >= 1000000) {
return (num / 1000000).toFixed(1).replace(/\.0$/, '') + 'Million';
}
if (num >= 1000) {
return (num / 1000).toFixed(1).replace(/\.0$/, '') + 'Thousand';
}
return num;
}
nFormatter;
I need to add this code to my other code but i am not sure how i am going to do this.
Here is my current code.
var gameProfit = 5000;
var tinyOwned = 0;
var tinyCost = 5000;
var tinyIncome = 0;
function tinyGamePlay() {
if (gameProfit >= tinyCost) {
tinyOwned++;
gameProfit -= tinyCost;
tinyIncome = 15000 * tinyOwned;
tinyCost = 5000 * tinyOwned;
document.getElementById('tiny-owned').innerHTML = tinyOwned;
document.getElementById('tiny-income').innerHTML = "Income : $ " + tinyIncome;
document.getElementById('tiny-cost').innerHTML = "Next Cost : $ " + tinyCost;
document.getElementById('currentProfit').innerHTML = "Profit : $ " + gameProfit;
}
}
tinyGamePlay;
So all of the my variable will be more than 1000 at one point so the formatter needs to be used on all my variables.
I dont mind using a JS plugin either if anyone knows of something that could help,
Can anyone help please?

You just need to call this nFormatter function when you are printing the output, see snipped below, for bigger numbers you can use http://jsfromhell.com/classes/bignumber :
function nFormatter(num) {
if (num >= 1000000000000) {
return (num / 1000000000000).toFixed(1).replace(/\.0$/, '') + ' Trillion';
}
if (num >= 1000000000) {
return (num / 1000000000).toFixed(1).replace(/\.0$/, '') + ' Billion';
}
if (num >= 1000000) {
return (num / 1000000).toFixed(1).replace(/\.0$/, '') + ' Million';
}
if (num >= 1000) {
return (num / 1000).toFixed(1).replace(/\.0$/, '') + ' Thousand';
}
return num;
}
var gameProfit = 5100;
var tinyOwned = 0;
var tinyCost = 5000;
var tinyIncome = 0;
function tinyGamePlay() {
if (gameProfit >= tinyCost) {
tinyOwned++;
gameProfit -= tinyCost;
tinyIncome = 15000 * tinyOwned;
tinyCost = 5000 * tinyOwned;
console.log(tinyCost);
document.getElementById('tiny-owned').innerHTML = nFormatter(tinyOwned);
document.getElementById('tiny-income').innerHTML = "Income : $ " + nFormatter(tinyIncome);
document.getElementById('tiny-cost').innerHTML = "Next Cost : $ " + nFormatter(tinyCost);
document.getElementById('currentProfit').innerHTML = "Profit : $ " + nFormatter(gameProfit);
}
}
tinyGamePlay();
<p id="tiny-owned"></p>
<p id="tiny-income"></p>
<p id="tiny-cost"></p>
<p id="currentProfit"></p>

Related

Javascript does not execute correctly

Good evening,
I am using Blockly to learn to programm.
In the exercise part of the code is not executed correctly. If "maandloon" is above > 2000, then there is a reduction of 25% on 'Kindergeld'. However if the result after the reduction is below 25 euro per child, then there is no reduction.
The problem is that calculation keeps using the 25% when maandloon >2000, even if the result afer reduction is below 25 euro per child.
This is my code:
var aantalKinderen, maandloon, kindergeld, kindergeldBasis, toeslag3ekind, toeslag5ekind, i;
do {
aantalKinderen=parseInt((parseFloat((output = window.prompt('Hoeveel kinderen?')) ? output : "")));
var blocktype_number = true;
if (output == null) {
window.alert("No empty input allowed");
break;
}
} while(isNaN(aantalKinderen));
do {
maandloon=(parseFloat((output = window.prompt('Wat is het maandloon?')) ? output : ""));
var blocktype_number = true;
if (output == null) {
window.alert("No empty input allowed");
break;
}
} while(isNaN(maandloon));
kindergeldBasis = 25;
toeslag3ekind = 12.5;
toeslag5ekind = 7.5;
kindergeld = kindergeldBasis * aantalKinderen;
if (aantalKinderen > 2) {
kindergeld = kindergeldBasis * aantalKinderen + (aantalKinderen - 2) * toeslag3ekind;
}
if (aantalKinderen > 4) {
kindergeld = kindergeldBasis * aantalKinderen + (aantalKinderen - 2) * toeslag3ekind + (aantalKinderen - 4) * toeslag5ekind;
}
if (maandloon <= 500) {
kindergeld = kindergeld * 1.25;
}
if (maandloon > 2000) {
kindergeld = kindergeld * 0.75;
} else {
if ((kindergeld * 0.75) / aantalKinderen < 25) {
kindergeld = kindergeld;
}
}
window.alert(String('Het kindergeld bedraagt ') + String(kindergeld)+'\n');
Can someone help me?
Thank you.
From what it sounds like you want to move your extra if check into the > 2000 statement. Otherwise it won't fire. Your if else statement is linear. It doesn't hit your else after > 2000 unless the conditional hasn't been matched by any of the previous if statements and the value is less than 2000. It does not run regardless or when the value was changed by a previous if condition.
var aantalKinderen, maandloon, kindergeld, kindergeldBasis, toeslag3ekind, toeslag5ekind, i;
do {
aantalKinderen=parseInt((parseFloat((output = window.prompt('Hoeveel kinderen?')) ? output : "")));
var blocktype_number = true;
if (output == null) {
window.alert("No empty input allowed");
break;
}
} while(isNaN(aantalKinderen));
do {
maandloon=(parseFloat((output = window.prompt('Wat is het maandloon?')) ? output : ""));
var blocktype_number = true;
if (output == null) {
window.alert("No empty input allowed");
break;
}
} while(isNaN(maandloon));
kindergeldBasis = 25;
toeslag3ekind = 12.5;
toeslag5ekind = 7.5;
kindergeld = kindergeldBasis * aantalKinderen;
if (aantalKinderen > 2) {
kindergeld = kindergeldBasis * aantalKinderen + (aantalKinderen - 2) * toeslag3ekind;
}
if (aantalKinderen > 4) {
kindergeld = kindergeldBasis * aantalKinderen + (aantalKinderen - 2) * toeslag3ekind + (aantalKinderen - 4) * toeslag5ekind;
}
if (maandloon <= 500) {
kindergeld = kindergeld * 1.25;
}
if (maandloon > 2000) {
kindergeld = kindergeld * 0.75;
if (kindergeld / aantalKinderen < 25) {
kindergeld = 25;
}
}
window.alert(String('Het kindergeld bedraagt ') + String(kindergeld)+'\n');

Prompt window won't open when clicking on button

I've got an assignment where I have to see if the entered number is an Armstrong number, the problem is when I click on the button the prompt window doesn't show up, and it only occurs when I have the rest of the function written out. When it is by itself the prompt window shows.
function armNum(){
var num = prompt("Enter a number between 0 and 999!: ");
var firstNum;
var secondNum;
var thirdNum;
if(num < 100 && num > 0)
{
firstNum = num/10;
secondNum = num%10;
var StrongNum = (firstNum**3) + (secondNum**3);
if( num == StrongNum)
{
document.getElementById("ispis").innerHTML = "nummber " + num + " is an armstrong number!"
}
else
{
document.getElementById("ispis").innerHTML = "number" + num + "is not an armstrong number!"
}
}
if(num > 99 && num < 1000)
{
firstNum = num/100;
secondNum = (num/10)%10;
thirdNum = num % 10;
var StrongNum = (firstNum**3) + (secondNum**3) = (thirdNum**3);
if( num == StrongNum)
{
document.getElementById("ispis").innerHTML = "nummber " + num + " is an armstrong number!"
}
else
{
document.getElementById("ispis").innerHTML = "number" + num + "is not an armstrong number!"
}
}
}
You have a mistake at this string (change "=" to "+"):
var StrongNum = (firstNum3) + (secondNum3) = (thirdNum**3);
You don`t call function
try to add after your function
armNum();
there is a error in tnis line = (firstNum**3) + (secondNum**3) = (thirdNum**3); you have used '=' instead off '+' & you
function armNum(){
var num = prompt("Enter a number between 0 and 999!: ");
var firstNum;
var secondNum;
var thirdNum;
if(num < 100 && num > 0)
{
firstNum = num/10;
secondNum = num%10;
var StrongNum = (firstNum**3) + (secondNum**3);
if( num == StrongNum)
{
alert( "nummber " + num + " is an armstrong number!")
}
else
{
alert( "number" + num + "is not an armstrong number!"); }
}
if(num > 99 && num < 1000)
{
firstNum = num/100;
secondNum = (num/10)%10;
thirdNum = num % 10;
var StrongNum = (firstNum**3) + (secondNum**3)+(thirdNum**3);
if( num == StrongNum)
{
alert( "nummber " + num + " is an armstrong number!");
}
else
{
alert("number" + num + "is not an armstrong number!");
}
}
}
<body onload=armNum()>
</body>

Lucky prizes game infinite loop?

I made a basic 'Lucky Prizes' game in Javascript and yet cannot work out how to stop it from infinitely looping. Is there anything I am obviously doing wrong as I am a beginner and the help would be appreciated.
var winNumber = 0;
var lossNumber = 0;
while (lossNumber < 10);
{
var randomNumber = Math.floor(Math.random() * 100);
if (randomNumber > 20 && randomNumber < 40) {
var winNumber = winNumber + 1;
} else
{
var lossNumber = lossNumber + 1;
}
}
console.log('Number of wins: ' + winNumber);
console.log('Number of losses: ' + lossNumber);
Many thanks
Actually, your entire problem is due to an errant semicolon in while (lossNumber < 10);
This causes the rest of the condition to not be evaluated so the loop never ends. Using var again inside the loops isn't necessary but it's also not the cause of your problem, the semicolon is.
var winNumber = 0;
var lossNumber = 0;
while (lossNumber < 10)
{
var randomNumber = Math.floor(Math.random() * 100);
if (randomNumber > 20 && randomNumber < 40) {
var winNumber = winNumber + 1;
} else
{
var lossNumber = lossNumber + 1;
}
}
console.log('Number of wins: ' + winNumber);
console.log('Number of losses: ' + lossNumber);
You redeclared the variables winNumber and lossNumber again.
Try this:
var winNumber = 0;
var lossNumber = 0;
while (lossNumber < 10)
{
var randomNumber = Math.floor(Math.random() * 100);
if (randomNumber > 20 && randomNumber < 40) {
winNumber = winNumber + 1;
}
else {
lossNumber = lossNumber + 1;
}
}
console.log('Number of wins: ' + winNumber);
console.log('Number of losses: ' + lossNumber);

Complex regular expression with validation rules and so on

Maybe I got killed here but I need to ask if this insane is possible through RegEx, see I have this Javascript/jQyery function for validates VAT number in Venezuela (RIF):
function(value) {
if (value === '') {
return true;
}
var $rif = value.val();
var $last_number = $rif.substr($rif.length - 1);
var $number = $rif.substr(0, 8);
$valid = /^([VEJPG]{1})([0-9]{9}$)/.test($rif_type + $rif);
if ($valid) {
if ($rif_type == "V") {
$sum = 1 * 4;
} else if ($rif_type == "E") {
$sum = 2 * 4;
} else if ($rif_type == "J") {
$sum = 3 * 4;
} else if ($rif_type == "P") {
$sum = 4 * 4;
} else if ($rif_type == "G") {
$sum = 5 * 4;
}
$n0 = $number.charAt(0) * 3;
$n1 = $number.charAt(1) * 2;
$n2 = $number.charAt(2) * 7;
$n3 = $number.charAt(3) * 6;
$n4 = $number.charAt(4) * 5;
$n5 = $number.charAt(5) * 4;
$n6 = $number.charAt(6) * 3;
$n7 = $number.charAt(7) * 2;
$sum += $n0 + $n1 + $n2 + $n3 + $n4 + $n5 + $n6 + $n7;
$mod = $sum % 11;
$last_val = 11 - $mod;
if ($last_val == 11 || $last_val == 10) {
$last_val = 0;
}
if ($last_number == $last_val) {
return true;
} else {
return false;
}
}
return false;
}
I'm asking if it's possible to write a RegEx to check the same and if so, how?
These are valid VAT numbers:
J298081775
J295809000
J298720620

one function in 2 controllers[JS]

Here is my question: I've got this little JS programm here in which are 2 controllers.. my problem is I need one function in both controllers (data.duration). Because one time I need the function for the features themselves and one time for the summary. Btw I get my informations via a JSON report and the function proofes itself if it is a feature or only a value. At the time the function is in the code 2 times...
So is there a way use the function in both controllers?
(function() {
var loader = ['$http',
function($http) {
return $http.get('report.json')
.success(function(data) {
function getFailedScenarioCount(feature) {
var failedScenarios = 0;
feature.scenarios.forEach(function(scenario) {
if (scenario.result.failedStepCount)
failedScenarios++;
});
return failedScenarios;
}
function getUnknownScenarioCount(feature) {
var unknownScenarios = 0;
feature.scenarios.forEach(function(scenario) {
if (scenario.result.unknownStepCount)
unknownScenarios++;
});
return unknownScenarios;
}
angular.forEach(data.features, function(feature) {
if (feature.scenarios.length) {
feature.result.failedScenarioCount = getFailedScenarioCount(feature);
feature.result.unknownScenarioCount = getUnknownScenarioCount(feature);
feature.result.passedScenarioCount = feature.result.scenarioCount - feature.result.failedScenarioCount - feature.result.unknownScenarioCount;
if (feature.result.failedScenarioCount === 0)
feature.result.failedScenarioCount = null;
if (feature.result.unknownScenarioCount === 0)
feature.result.unknownScenarioCount = null;
if (feature.result.passedScenarioCount === 0)
feature.result.passedScenarioCount = null;
}
feature.status = feature.result.failedScenarioCount ? "FAILED" : "OK";
angular.forEach(feature.scenarios, function(scenario) {
angular.forEach(scenario.steps, function(step) {
if (step.result.status === "undefined")
step.result.status = "unknown";
});
scenario.status = scenario.result.failedStepCount ? "failed" : (scenario.result.unknownStepCount ? 'unknown' : 'passed');
});
});
data.duration = function(feature) {
var day = 0;
var h = 0;
var min = 0;
var sec = 0;
var value = 0;
var substract = function(v, b) {
var result = v - (b);
return result;
};
if (isNaN(feature)) {
value = feature.result.duration;
} else {
value = feature;
}
console.log("value: " + value);
if (value % (1000000000 * 60 * 60 * 24) >= 0) //day
{
day = (value / (1000000000 * 60 * 60 * 24)) | 0;
value = substract(value, (day * (1000000000 * 60 * 60 * 24)));
}
if (value % (1000000000 * 60 * 60) >= 0) //hour
{
h = (value / (1000000000 * 60 * 60)) | 0;
value = substract(value, (h * (1000000000 * 60 * 60)));
if (h % 24 === 0 && h !== 0) {
day++;
h = 0;
}
}
if (value % (1000000000 * 60) >= 0) //minute
{
min = (value / (1000000000 * 60)) | 0;
value = substract(value, (min * (1000000000 * 60)));
if (min % 60 === 0 && min !== 0) {
h++;
min = 0;
}
}
if (value % (1000000000) >= 0) //second
{
sec = (value / (1000000000)) | 0;
value = substract(value, (sec * (1000000000)));
if (sec % 60 === 0 && sec !== 0) {
min++;
sec = 0;
}
}
if (day === 0 && h === 0 && min === 0 && sec === 0) {
var msec = 0;
if (value % 1000000 >= 0) {
msec = (value / 1000000) | 0;
}
return msec > 0 ? msec + 'ms' : '<1ms';
} else if (day > 0) {
return (' ' + '(' + day + 'Day/s) ' + ' ' + ' ' + h + ' ' + ':' + ' ' + min + ' ' + ':' + ' ' + sec);
} else {
return (' ' + h + ' ' + ':' + ' ' + min + ' ' + ':' + ' ' + sec);
}
};
});
}
];
var app = window.angular.module('cucumber', ['ui.bootstrap']);
app.config(['$routeProvider',
function($routeProvider) {
$routeProvider.when('/features', {
templateUrl: 'features.html',
controller: 'FeatureListCtrl',
resolve: {
report: loader
}
}).when('/feature/:featureId', {
templateUrl: 'feature.html',
controller: 'FeatureCtrl',
resolve: {
report: loader
}
}).otherwise({
redirectTo: '/features'
});
}
]);
app.controller('FeatureListCtrl', function($rootScope, $scope, $location, $filter, report) {
$scope.report = report.data;
$rootScope.reportDate = $scope.report.date;
$scope.duration = $scope.report.duration;
$scope.featureDetails = function(feature) {
$location.path('/feature/' + feature.id);
};
$scope.sum = function(features, field) {
if (!features) return null;
var sum = features.reduce(function(sum, feature) {
var value = parseInt(feature.result[field], 10);
return isNaN(value) ? sum : sum + value;
}, 0);
return sum > 0 ? sum : null;
};
$scope.$watch("searchText", function(query) {
$scope.filteredFeatures = $filter("filter")($scope.report.features, query);
});
$scope.isCollapsed = true;
});
app.controller('FeatureCtrl', function($rootScope, $scope, $location, $routeParams, report) {
$scope.duration = report.data.duration;
function getFeature(featureId, features) {
for (var i = 0; i < features.length; i++) {
if (featureId === features[i].id) {
return features[i];
}
}
}
$scope.feature = getFeature($routeParams.featureId, report.data.features);
$rootScope.reportDate = report.data.date;
});
}());
Pretty simple, write a service and inject it into both controllers.
app.service("utilityService", function () {
return {
duration: function (feature) {
...your code
}
}
});
Then inject it into each controller:
app.controller('FeatureListCtrl', function($rootScope, $scope, $location, $filter, report, utilityService) {
});
Then reference it:
utilityService.duration($scope.whatEverData)

Categories

Resources