最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Truncate float (not rounded) to 2 decimal places - Stack Overflow

programmeradmin1浏览0评论

Please, I need convert String into Float or Double in Javascript. But I don't want it round it. I want just fixed 2 decimal places Number which means input 0.996 return me 0.99 and not 1.

// 1. Convert number to float strip to 2 decimal places
var total = ',996' // (or 0.996 if you want, doesn't matter)
total = Math.round(parseFloat(
                   total.replace (',', '.')
)).toFixed(2);

console.log ( typeof total );
console.log ( total );

After this, total is not a number anymore. It's a String with value 1

It's possible to convert string into decimal number with 2 fixed places without rounding?

If you're interested about simple spent manager, I'm programmit it here

Thank you very much for any advice

Best Regards

Please, I need convert String into Float or Double in Javascript. But I don't want it round it. I want just fixed 2 decimal places Number which means input 0.996 return me 0.99 and not 1.

// 1. Convert number to float strip to 2 decimal places
var total = ',996' // (or 0.996 if you want, doesn't matter)
total = Math.round(parseFloat(
                   total.replace (',', '.')
)).toFixed(2);

console.log ( typeof total );
console.log ( total );

After this, total is not a number anymore. It's a String with value 1

It's possible to convert string into decimal number with 2 fixed places without rounding?

If you're interested about simple spent manager, I'm programmit it here https://codepen.io/littleTheRabbit/pen/JjYWjRG

Thank you very much for any advice

Best Regards

Share Improve this question edited Apr 25, 2020 at 15:55 user2864740 62.1k15 gold badges158 silver badges229 bronze badges asked Apr 25, 2020 at 15:42 Bambi BunnyBambi Bunny 1,4383 gold badges13 silver badges21 bronze badges
Add a ment  | 

1 Answer 1

Reset to default 5

This can be done by dropping the extra digits you don't want by using multiplication and division. For example, if you want 0.994 to be 0.99, you can multiply by 100 (to cover 2 decimal places), then truncate the number, and then divide it back by 100 to it to the original decimal place.

example:

  0.994 * 100 = 99.4
  99.4 truncated = 99.0
  99.0 / 100 = 0.99

So here is a function that will do that:

const truncateByDecimalPlace = (value, numDecimalPlaces) =>
  Math.trunc(value * Math.pow(10, numDecimalPlaces)) / Math.pow(10, numDecimalPlaces)

console.log(truncateByDecimalPlace(0.996, 2)) // 0.99
发布评论

评论列表(0)

  1. 暂无评论