简体   繁体   English

删除小数点前的前导0并返回数字-javascript

[英]remove leading 0 before decimal point and return as a number- javascript

Problem 问题

I need to return a number in the format of .66 (from an entered value which includes the leading zero, eg 0.66) 我需要返回.66格式的数字(从包含前导零的输入值(例如0.66)中返回)

It must be returned as an integer with the decimal point as the first character. 它必须以整数形式返回,以小数点为第一个字符。

what method in JavaScript can help me do this? JavaScript中有什么方法可以帮助我做到这一点?

What have I tried? 我尝试了什么?

I've tried converting it toString() and back to parseInt() but including the decimal point makes it return NaN. 我试过将其转换为String()并返回parseInt(),但包含小数点会使它返回NaN。

I've tried adding various radix (10, 16) to my parseInt() - also unsuccessful 我尝试将各种基数(10,16)添加到我的parseInt()中-也不成功

Sample Code 样例代码

const value = 0.66;

if(value < 1) {
    let str = value.toString().replace(/^0+/, '');
    // correctly gets '.66'
    return parseInt(str)
}

//result NaN

Expectations 期望

I expect an output of the value with the leading 0 removed eg 0.45 --> .45 or 0.879 --> .879 我希望输出值的前导0被删除,例如0.45-> .45或0.879-> .879

Current Observations 目前的观察

Output is NaN 输出为NaN

Issue #1: 0.66 is not an Integer. 问题1:0.66不是整数。 An Integer is a whole number, this is a floating-point number. 整数是整数,这是浮点数。

Issue #2: You cannot have a number in JavaScript that starts with a decimal point. 问题2:JavaScript中的数字不能以小数点开头。 Even if you change your parseInt to be parseFloat , it will still return 0.66 as a result. 即使将parseInt更改为parseFloat ,其结果仍将返回0.66。

What you're asking just isn't possible, if you want a number to start with a decimal point then it has to be a string. 您要问的是不可能的,如果您希望数字以小数点开头,那么它必须是字符串。

I tried a quick solution, you may try to do this: 我尝试了快速解决方案,您可以尝试执行以下操作:

let a = 0.45;
// split on decimal, at index 1 you will find the number after decimal
let b = a.toString().split('.')[1];

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM