Adding Decimal place into number with javascript - javascript

I've got this number as a integer 439980
and I'd like to place a decimal place in 2 places from the right. to make it 4399.80
the number of characters can change any time, so i always need it to be 2 decimal places from the right.
how would I go about this?
thanks

function insertDecimal(num) {
return (num / 100).toFixed(2);
}

Just adding that toFixed() will return a string value, so if you need an integer it will require 1 more filter. You can actually just wrap the return value from nnnnnn's function with Number() to get an integer back:
function insertDecimal(num) {
return Number((num / 100).toFixed(2));
}
insertDecimal(99552) //995.52
insertDecimal("501") //5.01
The only issue here is that JS will remove trailing '0's, so 439980 will return 4399.8, rather than 4399.80 as you might hope:
insertDecimal(500); //5
If you're just printing the results then nnnnnn's original version works perfectly!
notes
JavaScript's Number function can result in some very unexpected return values for certain inputs. You can forgo the call to Number and coerce the string value to an integer by using unary operators
return +(num / 100).toFixed(2);
or multiplying by 1 e.g.
return (num / 100).toFixed(2) * 1;
TIL: JavaScript's core math system is kind of weird

Another Method
function makeDecimal(num){
var leftDecimal = num.toString().replace('.', ''),
rightDecimal = '00';
if(leftDecimal.length > 2){
rightDecimal = leftDecimal.slice(-2);
leftDecimal = leftDecimal.slice(0, -2);
}
var n = Number(leftDecimal+'.'+rightDecimal).toFixed(2);
return (n === "NaN") ? num:n
}
makeDecimal(3) // 3.00
makeDecimal(32) // 32.00
makeDecimal(334) // 3.34
makeDecimal(13e+1) // 1.30
Or
function addDecimal(num){
var n = num.toString();
var n = n.split('.');
if(n[1] == undefined){
n[1] = '00';
}
if(n[1].length == 1){
n[1] = n[1]+'0';
}
return n[0]+'.'+n[1];
}
addDecimal(1); // 1.00
addDecimal(11); // 11.00
addDecimal(111); // 111.00
Convert Numbers to money.
function makeMoney(n){
var num = n.toString().replace(/\$|\,/g,'');
if(isNaN(num))
num = "0";
sign = (num == (num = Math.abs(num)));
num = Math.floor(num*100+0.50000000001);
cents = num%100;
num = Math.floor(num/100).toString();
if(cents<10)
cents = "0" + cents;
for (var i = 0; i < Math.floor((num.length-(1+i))/3); i++)
num = num.substring(0,num.length-(4*i+3))+','+num.substring(num.length-(4*i+3));
return (((sign)?'':'-') + '$' + num + '.' + cents);
}
One More.
function addDecimal(n){
return parseFloat(Math.round(n * 100) / 100).toFixed(2);
}

Related

Overwrite toFixed() with appropriate replacement to fix floating point error javascript

This is my attempt to fix the JavaScript toFixed() function...
Any input, ideas, corrections for possible errors are much appreciated!
Fix floating point inacurracy (example (35.355).toFixed(2) = 35.36, not 35.35)
No big additional libraries
Comprehensive function (readable by humans)
Mimics toFixed / i.e. outputs exactly the same (albeit with correction for floating point inac. or course)
This is my attempt -> Demo below (see console log)
Number.prototype.toFixed = function(fractionDigits) {
var digits = parseInt(fractionDigits) || 0;
var num = Number(this);
if( isNaN(num) ) {
return 'NaN';
}
var sign = num < 0 ? -1 : 1;
if (sign < 0) { num = -num; }
digits = Math.pow(10, digits);
num *= digits;
num = Math.round( Math.round(num * Math.pow(10,12)) / Math.pow(10,12) );
var finalNumber = sign * num / digits;
// add 0 after last decimal number (not 0) for as many as requested (fractionDigits)
// in else case, check if requested digits exceed actual, then add 0 (avoid 10.1 for toFixed(2))
if(fractionDigits > 0 && finalNumber.toString().indexOf('.') == -1){
// check that .00 is present
finalNumber = finalNumber.toString() + '.' + '0'.repeat(fractionDigits);
} else if(fractionDigits > finalNumber.toString().split('.')[1]?.length){
finalNumber = finalNumber.toString() + '0'.repeat((fractionDigits - finalNumber.toString().split('.')[1]?.length));
}
return finalNumber.toString(); // tofixed returns as string always, do the same
}
console.log('(35.355).toFixed(2)', (35.355).toFixed(2));
console.log('(35.1).toFixed(2)', (35.1).toFixed(2));
console.log('(35).toFixed(2)', (35).toFixed(2));
Number.prototype.toFixed = function(fractionDigits) {
//function toFixed(numberInput, fractionDigits){
var digits = parseInt(fractionDigits) || 0;
var num = Number(this);
if( isNaN(num) ) {
return 'NaN';
}
var sign = num < 0 ? -1 : 1;
if (sign < 0) { num = -num; }
digits = Math.pow(10, digits);
num *= digits;
num = Math.round( Math.round(num * Math.pow(10,12)) / Math.pow(10,12) );
var finalNumber = sign * num / digits;
// add 0 after last decimal number (not 0) for as many as requested (fractionDigits)
if(fractionDigits > 0 && finalNumber.toString().indexOf('.') == -1){
// check that .00 is present
finalNumber = finalNumber.toString() + '.' + '0'.repeat(fractionDigits);
} else if(fractionDigits > finalNumber.toString().split('.')[1]?.length){
finalNumber = finalNumber.toString() + '0'.repeat((fractionDigits - finalNumber.toString().split('.')[1]?.length));
}
return finalNumber.toString(); // tofixed returns as string always, do the same
}
console.log('post-fix | (35.355).toFixed(2)', (35.355).toFixed(2));
console.log('post-fix | (35.1).toFixed(2)', (35.1).toFixed(2));
console.log('post-fix | (35).toFixed(2)', (35).toFixed(2));
If it were me, I might have this string manipulation approach:
Number.prototype.toFixed = function(fractionDigits) {
var number = String(this);
var digits = fractionDigits || 0, length;
if(digits < 0 && digits > 100)
throw 'RangeError: toFixed() digits argument must be between 0 and 100';
var decimal = number.match(/(?<=\.)(\d*)/g);
var factor = Math.pow(10, digits);
if (decimal && decimal[0].length >= digits)
return String(Math.round(Number(number + '1') * factor) / factor);
else {
var length = digits - (decimal ? decimal[0].length : 0);
var delimiter = number.includes('.') || !length ? '' : '.';
return String(number) + delimiter + '0'.repeat(length);
}
}
function test() {
console.log((-35.555).toFixed(2))
console.log((-35.35).toFixed(2))
console.log((-35.9).toFixed(2))
console.log((-35).toFixed(2))
}
Note:
I think you're not going to encounter a string in your toFixed since it will not be triggered by it so you don't need isNaN check.
Catch beforehand when the parameter is less than 0 or greater than 100. This should throw an error like the original one.
Output:
Instead of rounding number num = Math.round( Math.round(num * Math.pow(10,12)) / Math.pow(10,12) ); here you try parsing it to integer.
Math.round will round the value depending on its factorial part greater or less than 0.5. parseInt will simply fetch integer part without rounding, as you are expecting here.
console.log('(35.355).toFixed(2)', (35.355).toFixed(2));
console.log('(35.1).toFixed(2)', (35.1).toFixed(2));
console.log('(35).toFixed(2)', (35).toFixed(2));
Number.prototype.toFixed = function(fractionDigits) {
//function toFixed(numberInput, fractionDigits){
debugger;
var digits = parseInt(fractionDigits) || 0;
var num = Number(this);
if( isNaN(num) ) {
return 'NaN';
}
var sign = num < 0 ? -1 : 1;
if (sign < 0) { num = -num; }
digits = Math.pow(10, digits);
num *= digits;
num = parseInt( Math.round(num * Math.pow(10,12)) / Math.pow(10,12) );
var finalNumber = sign * num / digits;
// add 0 after last decimal number (not 0) for as many as requested (fractionDigits)
if(fractionDigits > 0 && finalNumber.toString().indexOf('.') == -1){
// check that .00 is present
finalNumber = finalNumber.toString() + '.' + '0'.repeat(fractionDigits);
} else if(fractionDigits > finalNumber.toString().split('.')[1]?.length){
finalNumber = finalNumber.toString() + '0'.repeat((fractionDigits - finalNumber.toString().split('.')[1]?.length));
}
return finalNumber.toString(); // tofixed returns as string always, do the same
}
console.log('post-fix | (35.355).toFixed(2)', (35.355).toFixed(2));
console.log('post-fix | (35.1).toFixed(2)', (35.1).toFixed(2));
console.log('post-fix | (35).toFixed(2)', (35).toFixed(2));

how to create three random numbers in javascript and then tell input is odd or not?

how to create three random numbers in javascript and then tell input is odd or not?
To determine if odd:
num % 2;
That will return 0 or 1. If you want it to return true or false, then do
(num % 2) == 1;
Make a "isOdd" function and you can use it to check your random numbers against:
function isOdd(num) {
return (num % 2) == 1;
}
Use it like
function randomizer() {
var a = Math.floor((Math.random() * 10));
var b = Math.floor((Math.random() * 10));
var c = Math.floor((Math.random() * 10));
if (isOdd(a)) {
\\Give more points because it's odd
}
}
Here's a very simple working example: https://codepen.io/anon/pen/rqLVxM
to verify that all numbers are even use this function
function areEven(a,b,c){
return a%2==0 && b%2==0 && c%2==0
}
to verify that all numbers are odd use this function
function areOdd(a,b,c){
return a%2!=0 && b%2!=0 && c%2!=0
}
to verify that all numbers are are in sequence use this function :
function areInSequence(a,b,c){
var array = [a,b,c];
array.sort(function(a, b){return a - b});
var validity=false;
var i;
var length = array.length
for (i =0; i < length-1 ; i++) {
if((array [i+1] - array [i]) == 1){
validity=true;
}else validity=false;
}
return validity;
}
combine this functions in your code and if you need help leave a comment thanks!

Keep leading zero using javascript [duplicate]

This question already has answers here:
How can I pad a value with leading zeros?
(76 answers)
Closed 3 years ago.
Is there a way to prepend leading zeros to numbers so that it results in a string of fixed length? For example, 5 becomes "05" if I specify 2 places.
NOTE: Potentially outdated. ECMAScript 2017 includes String.prototype.padStart.
You'll have to convert the number to a string since numbers don't make sense with leading zeros. Something like this:
function pad(num, size) {
num = num.toString();
while (num.length < size) num = "0" + num;
return num;
}
Or, if you know you'd never be using more than X number of zeros, this might be better. This assumes you'd never want more than 10 digits.
function pad(num, size) {
var s = "000000000" + num;
return s.substr(s.length-size);
}
If you care about negative numbers you'll have to strip the - and read it.
UPDATE: Small one-liner function using the ES2017 String.prototype.padStart method:
const zeroPad = (num, places) => String(num).padStart(places, '0')
console.log(zeroPad(5, 2)); // "05"
console.log(zeroPad(5, 4)); // "0005"
console.log(zeroPad(5, 6)); // "000005"
console.log(zeroPad(1234, 2)); // "1234"
Another ES5 approach:
function zeroPad(num, places) {
var zero = places - num.toString().length + 1;
return Array(+(zero > 0 && zero)).join("0") + num;
}
zeroPad(5, 2); // "05"
zeroPad(5, 4); // "0005"
zeroPad(5, 6); // "000005"
zeroPad(1234, 2); // "1234" :)
You could extend the Number object:
Number.prototype.pad = function(size) {
var s = String(this);
while (s.length < (size || 2)) {s = "0" + s;}
return s;
}
Examples:
(9).pad(); //returns "09"
(7).pad(3); //returns "007"
From https://gist.github.com/1180489
function pad(a, b){
return(1e15 + a + '').slice(-b);
}
With comments:
function pad(
a, // the number to convert
b // number of resulting characters
){
return (
1e15 + a + // combine with large number
"" // convert to string
).slice(-b) // cut leading "1"
}
function zfill(num, len) {return (Array(len).join("0") + num).slice(-len);}
Just for fun (I had some time to kill), a more sophisticated implementation which caches the zero-string:
pad.zeros = new Array(5).join('0');
function pad(num, len) {
var str = String(num),
diff = len - str.length;
if(diff <= 0) return str;
if(diff > pad.zeros.length)
pad.zeros = new Array(diff + 1).join('0');
return pad.zeros.substr(0, diff) + str;
}
If the padding count is large and the function is called often enough, it actually outperforms the other methods...

Decimal to binary recursive function in JavaScript

I wanted to write a recursive function in js to calc the binary represenation of a decimal number.
I did manage to solve this by :
var t = (function f(n, s)
{
return((s = (n % 2) + s) && (n == 0)) ? s : f(Math.floor(n / 2), s);
})(4, '');
console.log(t);
Fiddle: http://jsbin.com/ihezev/3/edit
However, I can't get rid of the leading zero.
So if I execute the IIFE with 7 it yields : 0111 and I want 111.
How can I get rid of the leading 0?
(without string replace solution please. I want to keep it as much elegant as I can.. and I know I can do alert(Number(234).toString(2)) but this question is tagged as recursion.)
Here's a clean one I ported from python
const decToBi = num => num === 0 ? 0 : num % 2 + 10 * decToBi(Math.floor(num / 2));
console.log(decToBi(10)); //1010
A little bit changed but still elegant:
var t = (function f(n, s) {
return n === 0 ? s || "0" : f(~~(n / 2), (n % 2) + s);
})(7, ""); // "111"
function base10ToString(num, str = "") {
if (num === 0) {
return str;
}
if (num % 2 === 0) str = "0" + str;
else str = "1" + str;
return base10ToString(Math.floor(num / 2), str);
}
console.log(base10ToString(7));
You'll need to pass a parameter which represents whether you've produced a 1 yet. Whilst that parameter is false, you don't produce anything for a 0.
function binaryConversion(num) {
if (num === 0) {
return "";
}
return binaryConversion(Math.floor(num / 2)) + (num % 2).toString();
}

How can I generate a random number between 1 - 10 except that the random number can't be 3

How can I generate a random number between 1 - 10 except that the random number can't be 3
Get a random number between 1 and 9 and then add one if it's 3 or greater, or
better, just change any 3s into 10s.
function getNumber() {
return (n = 9 * Math.ceil(Math.random())) === 3? 10: n;
}
Based on this nice answer:
function getRandomInt (min, max) {
return Math.floor(Math.random() * (max - min + 1)) + min;
}
var rand;
while((rand = getRandomInt(1, 10)) == 3);
// rand is now your random number
function rand(begin, end) {
var result = Math.floor( Math.random() * (end - begin + 1) ) + begin;
return result === 3 ? rand(begin, end) : result;
}
function rand(){
var r = Math.ceil(Math.random() * 10);
if (r==3){
return rand()}
else
return r;
}
Here's a short, quick solution, using a self-executing function, that does what you need exactly but is only useful for the specific circumstance you describe:
var randOneToTenButNotThree = function () {
var result = Math.floor(Math.random() * 10) + 1; // PICK A NUMBER BETWEEN 1 AND 10
return (result !== 3) ? result : randOneToTenButNotThree(); // IF THE NUMBER IS NOT 3 RETURN THE RESULT, OTHERWISE CALL THIS FUNCTION AGAIN TO PICK ANOTHER NUMBER
}
var result = randOneToTenButNotThree(); // RESULT SHOULD BE A NUMBER BETWEEN 1 AND 10 BUT NOT 3
However, you could abstract this out to produce a random number in any given range, excluding any number of your choice:
var randExcl = function (lowest, highest, excluded) {
var result = Math.floor(Math.random() * (highest - lowest)) + lowest;
return (result !== excluded) ? result : randExcl();
}
var result = randExcl();
Just don't forget that if the function is renamed, you should also change the reference to it from within at the end of that return statement so that it can keep calling itself whenever it produces the excluded number.
This should work.
var r = 3;
while(r == 3) r = Math.ceil(Math.random() * 10);
function r(){a = Math.floor(Math.random() * 10) + 1; if (a==3) a++; return a;}

Categories

Resources