CalculateCircleArea Javascript - javascript

I have the following code:
function calculateCircleArea(r) {
// return the area of a circle with radius r
// round result to 3 decimal numbers
let area = (r * r * Math.PI);
return area.toFixed(Number(3));
}
console.log(calculateCircleArea(1));
It is returning the error:
AssertionError: expected '3.142' to equal 3.142
Can anyone help?

Use parseFloat convert string to decimal number
toFixed() return as string.So you need to convert to number
function calculateCircleArea(r) {
let area = (r * r * Math.PI);
return parseFloat(area.toFixed(3));
}
console.log(calculateCircleArea(1));
console.log(typeof(calculateCircleArea(1)));

Related

JavaScript: BigInteger implementation of a geometric sum

Say I have this equation here:
a * (1 - r ^ n) / (1 - r)
Basically, it is the formula for the sum of a geometric sequence. In our case, r is a decimal (float).
I am expecting the resulting number to be greater than the maximum safe integer, so BigInt will have to be used.
Is there a BigInt implementation of the Geometric Sum?
Thanks in advance!
This is what I have tried:
function geoSum(a, r, n) {
return BigInt(a * ((1 - r ** n) / (1 - n)));
}
Which already becomes Infinity before it can be converted into a BigInt.
Thanks in advance!
You should convert each of the parameters to BigInt before applying the operations:
function geoSum(a, r, n) {
const an = BigInt(a);
const rn = BigInt(r);
const nn = BigInt(n);
return an * ((1n - rn ** nn) / (1n - nn));
}
const result = geoSum(150, 151, 152);
console.log(String(result));
console.log(Number(result));
I just wrapped everything with BigInt.
function geoSum(a, r, n) {
return BigInt(BigInt(a) * (BigInt(BigInt(1) - BigInt(BigInt(r) ** BigInt(n))) /
BigInt(BigInt(1) - BigInt(n))));
}
geoSum(2,5,10)
returned:
2170138n
I don't know if the result makes sense to you.

What's wrong with this slice call in JS?

I write this line but get an error in response:
slice can't process there.
Why and how do I fix that?
function (row) {
var r = Math.round(Object.values(row)[3] / Object.values(row)[4]);
var t = Object.values(row)[2];
var s = Math.round((t - r) / t * 100);
return '<span id="up">${s.slice(0,2)}%</span>'
}
Your variable s is a number but the slice function requires a string. The solution would be to cast s into a string:
const slice = `${s}`.slice(0, 2);
Edit
To display a number with n decimals, you can multiply it by 10^n before rounding and then dividing it by the same number, cutting of anything after n decimals.
// display number with n decimals
const numberDisplay = (number, numberOfDecimals) => Math.round(number * Math.pow(10, numberOfDecimals)) / Math.pow(10, numberOfDecimals);
// your desired number display
const slice = numberDisplay(s, 2);

JavaScript round error ToFixed, NumberPrototypeRound

I'm tried many things but I still have a problem,
example: 4.3725 * 350 = 1530.38 but my result is 1530.37 ;/
I tried this:
Number.prototype.round = function(places) {
return +(Math.round(this + "e+" + places) + "e-" + places);
}
and toFixed.
You could use toPrecision(). This returns a string which you can just convert back to a Number and round.
The problem was toFixed() rounds numbers like that: 3.65.toFixed(1) => 3.6
Math.round(): https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/round
Here an example:
function roundTo(number, digits) {
var roundHelp = Math.pow(10, digits); // needed to round to correct number of decimals
number = Number(number.toPrecision(15));
return Math.round(number * roundHelp)/roundHelp;
// if you want the exact number of digits use this return statement:
// return (Math.round(number * roundHelp)/roundHelp).toFixed(digits);
}
var x = roundTo(4.3725 * 350, 2); // x = 1530.38
var y = roundTo(4.2970 * 535, 2); // y = 2298.9

How to round a number with multiple decimal places. Javascript

I am trying to create a function that can take a number and the number of decimal places and round the number to the exact decimal places that are going to be given.
I am using parseInt(prompt()) in order to gave the number and the number of decimal places.
For example,
round(3.141519, 2) -> 3.14
round(5986.32456, 4) -> 5986.3246
Can someone help me with this?
You can use toFixed
check the following
console.log(3.141519.toFixed(2))
console.log(5986.32456.toFixed(4))
Here is a short function that will allow you to specify the precision and returns a number:
function round(number, places) {
number = parseFloat(number, 10);
var e = parseInt(places || 2, 10);
var m = Math.pow(10, e);
return Math.floor(number * m) / m;
}
Or a slightly shorter ES6 function:
const round = (number, places=2) => {
const m = Math.pow(10, places);
return Math.floor(number * m) / m;
}

Rounding up to the nearest 0.05 in JavaScript

Question
Does anyone know of a way to round a float to the nearest 0.05 in JavaScript?
Example
BEFORE | AFTER
2.51 | 2.55
2.50 | 2.50
2.56 | 2.60
Current Code
var _ceil = Math.ceil;
Math.ceil = function(number, decimals){
if (arguments.length == 1)
return _ceil(number);
multiplier = Math.pow(10, decimals);
return _ceil(number * multiplier) / multiplier;
}
Then elsewhere...
return (Math.ceil((amount - 0.05), 1) + 0.05).toFixed(2);
Which is resulting in...
BEFORE | AFTER
2.51 | 2.55
2.50 | 2.55
2.56 | 2.65
Multiply by 20, then divide by 20:
(Math.ceil(number*20)/20).toFixed(2)
Rob's answer with my addition:
(Math.ceil(number*20 - 0.5)/20).toFixed(2)
Otherwise it always rounds up to the nearest 0.05.
** UPDATE **
Sorry has been pointed out this is not what the orig poster wanted.
I would go for the standard of actually dividing by the number you're factoring it to, and rounding that and multiplying it back again after. That seems to be a proper working method which you can use with any number and maintain the mental image of what you are trying to achieve.
var val = 26.14,
factor = 0.05;
val = Math.round(val / factor) * factor;
This will work for tens, hundreds or any number. If you are specifically rounding to the higher number then use Math.ceil instead of Math.round.
Another method specifically for rounding just to 1 or more decimal places (rather than half a place) is the following:
Number(Number(1.5454545).toFixed(1));
It creates a fixed number string and then turns it into a real Number.
I would write a function that does it for you by
move the decimal over two places (multiply by 100)
then mod (%) that inflatedNumber by 5 and get the remainder
subtract the remainder from 5 so that you know what the 'gap'(ceilGap) is between your number and the next closest .05
finally, divide your inflatedNumber by 100 so that it goes back to your original float, and voila, your num will be rounded up to the nearest .05.
function calcNearestPointZeroFive(num){
var inflatedNumber = num*100,
remainder = inflatedNumber % 5;
ceilGap = 5 - remainder
return (inflatedNumber + ceilGap)/100
}
If you want to leave numbers like 5.50 untouched you can always add this checker:
if (remainder===0){
return num
} else {
var ceilGap = 5 - remainder
return (inflatedNumber + ceilGap)/100
}
You need to put -1 to round half down and after that multiply by -1 like the example down bellow.
<script type="text/javascript">
function roundNumber(number, precision, isDown) {
var factor = Math.pow(10, precision);
var tempNumber = number * factor;
var roundedTempNumber = 0;
if (isDown) {
tempNumber = -tempNumber;
roundedTempNumber = Math.round(tempNumber) * -1;
} else {
roundedTempNumber = Math.round(tempNumber);
}
return roundedTempNumber / factor;
}
</script>
<div class="col-sm-12">
<p>Round number 1.25 down: <script>document.write(roundNumber(1.25, 1, true));</script>
</p>
<p>Round number 1.25 up: <script>document.write(roundNumber(1.25, 1, false));</script></p>
</div>
I ended up using this function in my project, successfully:
roundToNearestFiveCents( number: any ) {
return parseFloat((Math.round(number / 0.05) * 0.05).toFixed(2));
}
Might be of use to someone wanting to simply round to the nearest 5 cents on their monetary results, keeps the result a number, so if you perform addition on it further it won't result in string concatenation; also doesn't unnecessarily round up as a few of the other answers pointed out. Also limits it to two decimals, which is customary with finance.
My solution and test:
let round = function(number, precision = 2, rounding = 0.05) {
let multiply = 1 / rounding;
return parseFloat((Math.round(number * multiply) / multiply)).toFixed(precision);
};
https://jsfiddle.net/maciejSzewczyk/7r1tvhdk/40/
Even though the OP is not explicit about banker rounding, rounding up to the nearest $0.05 (5 cents) should be compatible with banker rounding. What suggested by Arth is more accurate than the accepted answer by Rob W.
(Math.ceil(number*20 - 0.5)/20).toFixed(2)
With banker rounding, you need a basic banker rounding function as suggested at Gaussian/banker's rounding in JavaScript, and I rewrite in TypeScript:
static bankerRound(num: number, decimalPlaces?: number) {
const d = decimalPlaces || 0;
const m = Math.pow(10, d);
const n = +(d ? num * m : num).toFixed(8);
const i = Math.floor(n), f = n - i;
const e = 1e-8;
const r = (f > 0.5 - e && f < 0.5 + e) ?
((i % 2 === 0) ? i : i + 1) : Math.round(n);
return d ? r / m : r;
}
static roundTo5cents(num: number) {
const r = bankerRound(Math.ceil(num * 20 - 0.5) / 20, 2);
return r;
}
The correctness of this algorithm could be verified through MBS Online, e.g. http://www9.health.gov.au/mbs/ready_reckoner.cfm?item_num=60

Categories

Resources