简体   繁体   中英

How to convert a floating number to fixed floating number using JavaScript

For example, I want to calculate 3/6. 3/6 answer is a 0.5 floating number. When I fixed this number with the javascript toFixed(6) method it returned '0.500000'. The problem is that '0.500000' is a string. But I want a floating number with 6 digits after the dot(.). How can I do that? I tried this but it's won't work.

parseFloat((3/6).toFixed(6))
//output = 0.5 but i want 0.500000

Well,

parseFloat((3/6).toFixed(6))
//output = 0.5 means everything after .5 is 0

If you print it to the console it will remove the unnecessary zero. When you need to print up to 5 or 10 decimal points, you have to convert the number into a string using the toFixed method.

Why are you using toFixed inside the parseFloat() because of that it is returning you 0.5

Do this

let a = parseFloat((3/6).toFixed(6))
console.log(a)

I updated my answer. I did not get that you wanted to use the output as a number. I don't think that what you want to achieve is possible. It's possible only if you keep you value as a string.

const numb = 3/6;
console.log(numb.toFixed(6));

For documentation: https://developer.mozilla.org/fr/docs/Web/JavaScript/Reference/Global_Objects/Number/toFixed

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM