Pedro Araujo Jorge
Pedro Araujo Jorge

Reputation: 686

Mask number in form input to display only two decimals but save original value

I'm trying to format a number in a form input to display only two decimals BUT still keep (save) the original value. I need to do this because if I simply round the number and save it there will be incorrect values down the line. Plus the customer only wants to see two decimals at most.

I tried using this: https://igorescobar.github.io/jQuery-Mask-Plugin/ and this: https://github.com/RobinHerbots/Inputmask but both these plugins will ignore the original value and just format it to "*.00". Ex: 134.277 will become 1342.77, which is very wrong.

I also tried this but unfortunately it just doesn't work: http://csspre.com/rounding-numbers/

Is it possible to round a number for display only?

Upvotes: 0

Views: 1599

Answers (2)

Ayo K
Ayo K

Reputation: 1774

Use toFixed to do your rounding

function doCustomRounding(obj){
    $("#"+obj.id).data("value", obj.value)
    $("#"+obj.id).val(Number(obj.value).toFixed(2));
}

function getOriginalValue(id){
    alert("original Value: "+$("#"+id).data("value"))
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.2.3/jquery.min.js"></script>
<input id="formattedNo" value = "0" type="number" onchange="doCustomRounding(this)" data-value="0" /><button onclick="getOriginalValue('formattedNo')">Get Original Value</button>

See above working snippet. Enter a number with decimal places then remove focus from the textbox.

EDIT

I used the data attribute to store the original value to avoid having to store in variables for each new input element

Upvotes: 1

Aster
Aster

Reputation: 23

You can use the toFixed() method when you are printing the value.

Documentation on toFixed(): https://www.w3schools.com/jsref/jsref_tofixed.asp

Upvotes: 0

Related Questions