top of page
Writer's pictureWeb Coding

How to create a percentage to decimal converter

Updated: Sep 10, 2020

Learn how to create a percentage to decimal converter with HTML, CSS and JavaScript

HTML

<!DOCTYPE html>
<html lang="en">
<head>
 <meta charset="UTF-8">
 <meta name="viewport" content="width=device-width, initial-scale=1.0">
 <title>Calc</title>
 <link rel="stylesheet" href="style.css">
</head>
<body>
 <div>
 <h1>Convert Decimal to Percentage and vice versa</h1>
        Conversion Method: <select name="convertType" id="convertType">
 <option value="Percent">To Percentage</option>
 <option value="Decimal">To Decimal</option>
 </select> <br>
        Value to Convert: <input type="text" name="valueToConvert" id="valueToConvert"> <br>
 <button type="button" id="convertBtn">Convert</button>

 <div>Converted Value is <span id="convertedValue"></span></div>

 </div>

 <script src="script.js"></script>
</body>
</html>

CSS

body{
 min-height100vh;
 displayflex;
 align-itemscenter;
 justify-contentcenter;
}

JavaScript

let conversionType = document.getElementById('convertType');
let numberToConvert = document.getElementById('valueToConvert');
let convertBtn = document.getElementById('convertBtn');
let valueDisplay = document.getElementById('convertedValue');

convertBtn.addEventListener('click'convert)

function convert(){
 let result = 0;
 if(conversionType.value === 'Percent'){
 result = parseFloat(numberToConvert.value) * 100;
 valueDisplay.innerHTML = result + "%"
    } else {
 result = parseFloat(numberToConvert.value) / 100;
 valueDisplay.innerHTML = result.toFixed(2);
    }
}

If you found this blog post helpful don’t forget to check out my other projects and if you want more content follow me on


YouTube: https://www.youtube.com/channel/UC2nxqB2usQIS2c8zwVZKWEQ

Instagram: https://www.instagram.com/coding_for_the_web/

Twitter: https://twitter.com/LearnWebCoding

9 views

Comments


bottom of page