'How can I parse a string as an integer and keep decimal places if they are zeros?

I have these strings: "59.50" & "30.00"

What I need to do is convert them to integers but keep the trailing zeros at the end to effectively return:

59.50
30.00

I've tried:

Math.round(59.50 * 1000) / 1000
Math.round(30.00 * 1000) / 1000

but ended up with

59.5
30

I'm assuming I need to use a different method than Math.round as this automatically chops off trailing zeros.

I need to keep these as integers as they need to be multiplied with other integers and keep two decimals points. T thought this would be fairly straight forward but after a lot of searching I can't seem to find a solution to exactly what I need.

Thanks!



Solution 1:[1]

Your premise is flawed. If you parse a number, you are converting it to its numerical representation, which by definition doesn't have trailing zeros.

A further flaw is that you seem to think you can multiply two numbers together and keep the same number of decimal places as the original numbers. That barely makes sense.

It sounds like this might be an XY Problem, and what you really want to do is just have two decimal places in your result.

If so, you can use .toFixed() for this:

var num = parseFloat("59.50");
var num2 = parseFloat("12.33");
var num3 = num * num2

console.log(num3.toFixed(2));  // 733.64

Solution 2:[2]

Whenever you want to display the value of the variable, use Number.prototype.toFixed(). This function takes one argument: the number of decimal places to keep. It returns a string, so do it right before viewing the value to the user.

console.log((123.4567).toFixed(2)); // logs "123.46" (rounded)

Solution 3:[3]

To keep the decimals - multiply the string by 1 example : "33.01" * 1 // equals to 33.01

Solution 4:[4]

Seems you are trying to retain the same floating point, so better solution will be some thing like

parseFloat(string).toFixed(string.split('.')[1].length);

Solution 5:[5]

If you want numbers with decimal points, you are not talking about integers (which are whole numbers) but floating point numbers.

In Javascript all numbers are represented as floating point numbers.

You don't need the trailing zeros to do calculations. As long as you've got all the significant digits, you're fine.

If you want to output your result with a given number of decimal values, you can use the toFixed method to transform your number into a formatted string:

var num = 1.5
var output = num.toFixed(2) // '1.50'
// the number is rounded
num = 1.234
output = num.toFixed(2) // '1.23'
num = 1.567
output = num.toFixed(2) // '1.57'

Here's a more detailed description of toFixed: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number/toFixed

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1
Solution 2 rhino
Solution 3 peanutz
Solution 4 Shaggy
Solution 5 user2465896