The Number Data Type
To declare a variable that holds a decimal number, you can simply assign it like this:
var myDecimal = 3.14;
You can perform various mathematical operations on decimal numbers using arithmetic operators like addition, subtraction, multiplication, and division.
Rounding Decimal Numbers
- toFixed(): This method returns a string representation of the number with the specified number of digits after the decimal point.
- toPrecision(): This method returns a string representation of the number with the specified total length (including both integer and fractional parts).
var myNumber = 3.14159; console.log(myNumber.toFixed(2)); // Output: 3.14 console.toPrecision(4)); // Output: 3.142
Limitations of the Number Data Type
console.log(0.1 + 0.2); // Output: 0.30000000000000004
The String Data Type
In some cases, you may need to treat decimal numbers as strings, especially when dealing with currency values or displaying numbers in a specific format. In such scenarios, you can store decimal numbers as strings using the String data type.
var myDecimalAsString = "3.14";
Note that performing mathematical operations on strings will result in concatenation rather than arithmetic operations.
Converting Strings to Decimal Numbers
If you have a string representing a decimal number and you need to perform mathematical operations on it, you can convert it to a decimal number using the parseFloat() or Number() functions.
var myString = "3.14"; var myNumber = parseFloat(myString); console.log(myNumber); // Output: 3.14
Alternatively, you can use the unary plus operator (+) to convert a string to a decimal number:
var myString = "3.14"; var myNumber = +myString; console.14