Hi! I’m trying to figure out how I can get a Math.round() result to output a hundredth decimal if that decimal rounds to a tenth (hard to explain, sorry).
Basically, if you’re calculating the percentage of a cash price, and the rounded product is, say, “$14.90”, the Math.round() will output “14.9” instead of “14.90”. It drops the 0 since it is unnecessary, but this isn’t aesthetically pleasing for, say, an e-commerce page. How could I get the output to generate 2 numbers after the decimal, even if the result is an even tenth of a decimal?
I’ve tried looking up solutions but I clearly don’t know how to articulate my question so I’m drawing blanks
If you are dealing with numbers, you are not going to see trailing zeros. If, however, you are converting your numbers to strings (for display) then you can use toFixed()
You can also use toLocaleString()
to format currency.
say your opinion about this code
I am learning JavaScript. just try to implement same without using default method
function selectHomanyDigitYouNeedAfetrDot(num, n) {
num = num + ''
num = num.split('');
var indexOfDot = num.indexOf('.')
var copyNumberAFterDot = num.slice(indexOfDot, indexOfDot + n + 1)
var copyNumberBeforerDot = num.slice(0, indexOfDot)
var requiredValue = copyNumberBeforerDot + copyNumberAFterDot;
requiredValue = requiredValue.replace(/[,]/g, '')
requiredValue = Number(requiredValue)
return requiredValue;
}
var a = selectHomanyDigitYouNeedAfetrDot(12345.2567, 3)
console.log(a)