How to extract decimal number from string using JavaScript
Asked Answered
D

6

12

I want to extract decimal number 265.12 or 0.0 from alphanumeric string (say amount) having value $265.12+ or $265.12- or $0.0+ or $0.0- and use it apply struts logic tag in JSP. Not sure how to extract number maybe with help of JavaScript.

Definitely answered 2/5, 2012 at 10:22 Comment(0)
U
33

You can use regex like this,

Live Demo

var amount = "$265.12+";
var doublenumber = Number(amount.replace(/[^0-9\.]+/g,""));
Underwood answered 2/5, 2012 at 10:25 Comment(0)
V
12

Without error checks, following will do:

var string = "$123123.0980soigfusofui"
var number = parseFloat(string.match(/[\d\.]+/))

123123.098

Vest answered 2/5, 2012 at 10:27 Comment(1)
I believe the regex can be shortened to /[\d.]+/ - stumbled upon that in JSMalchy
D
-1

Try this also,

<script type="text/javascript">
function validate(){
    var amount =  $("#amount").val();
    alert(amount.split(".")[1]);
} </script>
</head> 
<body>
<input type="hidden" name="amount" id="amount" value="25.50">
<input type="submit" onclick="validate();">
Dissolve answered 2/5, 2012 at 10:38 Comment(0)
O
-1

A more elegant solution and also a method to avoid the 0.7700000004 javascript math do this:

var num = 15.3354; Number(String(num).substr(String(num).indexOf('.')+1));

The result will always be the exact number of decimals. Also a prototype for easier use

Number.prototype.getDecimals = function () { return Number(String(this).substr(String(this).indexOf('.')+1)); }

so now just 15.6655.getDecimals() ==> 6655

Owlet answered 29/10, 2015 at 18:6 Comment(0)
L
-2

You might be interested in this library for formatting money http://josscrowcroft.github.com/accounting.js/

Lesialesion answered 2/5, 2012 at 10:28 Comment(2)
How could he when he needs to extract, not print?Vest
there's a method called unformat() that returns number. E.g. accounting.unformat("$ 12,345,678.90"); // 12345678.9Lesialesion
M
-3

use :

var str = parseFloat("$265.12".match(/[\d\.]+/))
alert(str % 1); => 0.12000000000000455
Misunderstanding answered 2/5, 2012 at 10:32 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.